我正在尝试运行此查询,但它只输出包含项目的类别的结果,而不是所有类别。这是我的问题:
SELECT categories.`id` as `cat_id`, categories.`title` as `cat_title`, COUNT(tutorials.`id`) as `total`
FROM `tutorial_categories` as `categories`, `tutorials`
WHERE tutorials.`category` = categories.id
GROUP BY `cat_id`
有人能引导我朝着正确的方向前进吗?感谢。
答案 0 :(得分:2)
SELECT
categories.id ,
categories.title,
COUNT(*) as total
FROM tutorial_categories as categories
LEFT JOIN tutorials
on tutorials.category = categories.id
GROUP BY categories.id
答案 1 :(得分:0)
您需要使用LEFT JOIN
。您的隐式连接语法会生成内部联接insetad:
SELECT
categories.`id` as `cat_id`,
categories.`title` as `cat_title`,
COUNT(tutorials.`id`) as `total`
FROM
`tutorial_categories` `categories` LEFT JOIN `tutorials` ON categories.id = tutorials.category
GROUP BY `cat_id`
答案 2 :(得分:0)
您正在寻找here所述的外部联接:“外部联接不要求两个连接表中的每条记录都有匹配的记录”
答案 3 :(得分:0)
您需要使用外部联接重新设置查询,而不是使用WHERE
像这样的东西
SELECT categories.`id` as `cat_id`, categories.`title` as `cat_title`, COUNT(tutorials.`id`) as `total`
FROM `tutorial_categories` as `categories`, `tutorials`
LEFT OUTER JOIN tutorials.`category` = categories.id
GROUP BY `cat_id`
答案 4 :(得分:-2)
您设置了WHERE tutorials.
类别= categories.id
,因此它只会返回符合该条件的行。删除它,它应该返回“所有类别”。
SELECT categories.`id` as `cat_id`, categories.`title` as `cat_title`, COUNT(tutorials.`id`) as `total`
FROM `tutorial_categories` as `categories`, `tutorials`
GROUP BY `cat_id`