[英]SQL Selecting count from join returning 0 instead of null result
I have a query that gets data and also joins another table (A) and counts the rows in that join table (B).我有一个查询,它获取数据并连接另一个表 (A) 并计算该连接表 (B) 中的行数。 However if the main table (A) is empty I want the query to return nothing.
但是,如果主表 (A) 为空,我希望查询不返回任何内容。 However it is returning a result of null for id and date and an integer value of 0 for users instead of a null row.
但是,它为 id 和 date 返回 null 结果,为用户返回整数值 0 而不是 null 行。 How do I get an empty result instead of it returning something?
如何获得空结果而不是返回某些内容?
Returning:返回:
id | date | users
null | null | 0
SQL Code SQL 代码
SELECT
`sessions`.`id`,
`sessions`.`date`,
COUNT( sessions_users.id ) AS users
FROM
`sessions`
LEFT JOIN `sessions_users` ON `sessions`.`id` = `sessions_users`.`sessions_id`
An aggregate query without a group by
clause always returns a single record, regardless of the content of the underlying result set (and even if it is empty).没有
group by
子句的聚合查询总是返回单个记录,无论底层结果集的内容如何(即使它是空的)。
But, since you have non-aggregated columns in the select
clause ( sessions.id
and sessions.date
), your query is missing a group by
clause anyway.但是,由于您在
select
子句( sessions.id
和sessions.date
)中有非聚合列,因此您的查询无论如何都缺少group by
子句。 In non-ancient versions in MySQL, where sql mode ONLY_FULL_GROUP_BY
is enabled by default, this is a syntax error.在MySQL中的非古版本中,默认启用sql模式
ONLY_FULL_GROUP_BY
,这是一个语法错误。
Consider:考虑:
SELECT
`sessions`.`id`,
`sessions`.`date`,
COUNT( sessions_users.id ) AS users
FROM
`sessions`
LEFT JOIN `sessions_users` ON `sessions`.`id` = `sessions_users`.`sessions_id`
GROUP BY
`sessions`.`id`,
`sessions`.`date`
This will produce one record per session id and date, along with the count of matching records in sessions_users
.这将产生每个会话ID和日期一个记录,在匹配记录的计数一起
sessions_users
。 If there are no records in sessions
, the query will return an empty result set.如果
sessions
中没有记录,则查询将返回一个空结果集。
If I understand correctly, instead of NULL
, you want something like this:如果我理解正确,而不是
NULL
,你想要这样的东西:
id | date | users
| | 0
If so, just simply use IFNULL()
in your SELECT
as such:如果是这样,只需在
SELECT
使用IFNULL()
即可:
SELECT
IFNULL(`sessions`.`id`,' ') as id,
IFNULL(`sessions`.`date`,' ') as date,
....
There are also a few other ways to achieve this using just IF()
or CASE ..
but IFNULL
is very straight forward.还有一些其他方法可以仅使用
IF()
或CASE ..
来实现这一点CASE ..
但IFNULL
非常简单。
BUT if you don't want to see any NULL
and 0
values, change your LEFT JOIN
to INNER JOIN
and you're done.但是,如果您不想看到任何
NULL
和0
值,请将您的LEFT JOIN
更改为INNER JOIN
,您就完成了。
From your description, it sounds like you want an inner join:从您的描述来看,您似乎想要一个内部连接:
SELECT s.id, s.date, COUNT(*) as users
FROM sessions s JOIN
sessions_users su
ON su.id = su.sessions_id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.