【发布时间】:2016-05-01 18:02:35
【问题描述】:
我有两张桌子:
debates
----------------------
id | name
----------------------
1 | why is that?
2 | why is the other?
opinions
---------------------
id | debate | opinion
---------------------
1 | 1 | because
2 | 1 | NULL
如果我使用 left join ON opinion.debate =debates.id 我可以得到两个辩论 (1, 2)。
如果我在 left join 上使用 where 子句 WHERE (opinions.opinion != '' AND opinion.opinion IS NOT NULL) 我只得到 id = 1 的辩论
如何获得两条记录但仍然保留条件,因为我使用它来计算记录?
例如。查询:
SELECT
debates.id,
COUNT(opinions.id) AS total_opinions
FROM debates
LEFT JOIN
`opinions` ON `opinions`.`debate` = `debates`.`id`
WHERE
`opinions`.`opinion` IS NOT NULL AND `opinions`.`opinion` != ''
GROUP BY
`debates`.`id`
应该返回:
debates
-------------------
id | total_opinions
-------------------
1 | 1
2 | 0
【问题讨论】:
-
那么你怎么能得到辩论 2 你坚持认为 opinions.opinion IS NOT NULL ?首先左连接的要点是允许意见.意见为空,以便出现辩论 2。
标签: mysql join left-join where ambiguity