简体   繁体   中英

SQL returning NULL instead of 0 rows

SELECT max(s.id), c.id, s.time, s.rankxp, s.score, s.kills, s.deaths, s.headshots, s.rank 
FROM clients c, stats s 
WHERE c.id = s.client_id  && s.client_id = 123

This query works fine if the client_id can be found in the stats table. However if the client_id can't be found in the stats table, the query is returning null instead of 0 rows.

How can I make this query return 0 rows instead of null when the client isn't found in the stats table?

If client ID always exists in clients table, just use a left join.

SELECT max(s.id), c.id, s.time, s.rankxp, s.score, s.kills, s.deaths, s.headshots, s.rank FROM clients c Left Join stats s on c.id = s.client_id Where c.id=123

This will give you a NULL in the max(s.id) field though.

I suppose you're trying to get latests stats for the client, to do this you don't need to do any joins, try this one:

SELECT s.id, s.client_id, s.time, s.rankxp, s.score, s.kills, s.deaths, s.headshots, s.rank 
FROM stats s 
WHERE s.client_id = 123
ORDER BY s.id DESC
LIMIT 1

I'm able to force a record with 0 values to be returned by using a duplicate sql statement unioned with the first. Such as:

SELECT 0 ID, 123 ClientID, 0 STime, 0 RankXP, 0 Score, 0 Kills, 0 Deaths, 0 Headshots, 0 rank
from stats s
where s.client_id = 123
UNION
select s.id ID, s.client_id ClientID, s.time STime, s.rankxp RankXP, s.score Score, s.kills Sills, s.deaths Deaths, s.headshots Headshots, s.rank Rank
from stats s
where s.client_id = 123

In my case, I encase the whole query within another query which selects the sum, count or max of the query elements, and refers to the main query as "Inner-table".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM