我正在尝试创建一个SQL查询,它显示类别以及该类别中有多少个线程的计数。
这就是我得到的:
SELECT categories.category_name, categories.category_id, COUNT(*)
AS 'threadCount' FROM threads
RIGHT OUTER JOIN categories
ON categories.category_id = threads.thread_category_id
GROUP BY categories.category_name, categories.category_id
它有点工作,但是,threadCount中的结果总是大于或等于1,即使那里没有线程。
正如您在上面的图片中所看到的,每个类别似乎都附加了一个线程。但问题是,只有'类别1'有线程,所有其他类别都附加了0个线程,所以它们应该显示0而不是1。
答案 0 :(得分:1)
联接中的Outer
包括所有类别,甚至包括未与任何线程相关联的类别,这就是为什么你至少有1个。
SELECT categories.category_name, categories.category_id, COUNT(*)
AS 'threadCount' FROM threads
RIGHT OUTER JOIN categories
ON categories.category_id = threads.thread_category_id
GROUP BY categories.category_name, categories.category_id
我会把它作为,
SELECT categories.category_name, categories.category_id,
(SELECT COUNT(*) FROM threads WHERE
categories.category_id = threads.thread_category_id) AS 'threadCount'
FROM categories
我直接计算每个类别的线程,并将它们连接起来。
答案 1 :(得分:0)
因为你正在做右外连接,当你没有相应的线程时,null也被计为1。按以下方式运行查询以查看我的意思
SELECT categories.category_name, categories.category_id
AS 'threadCount' FROM threads
RIGHT OUTER JOIN categories
ON categories.category_id = threads.thread_category_id
或者您可以通过更改此类查询来排除null计为1,
SELECT categories.category_name, categories.category_id, COUNT(threads.thread_category_id)
AS 'threadCount' FROM threads
RIGHT OUTER JOIN categories
ON categories.category_id = threads.thread_category_id
GROUP BY categories.category_name, categories.category_id