我的数据库是这样的:
table1(article)
id | name | description | cat_id
0 | val1 | desc1 | 1
1 | val2 | desc2 | 2
2 | val3 | desc3 | 1
3 | val4 | desc4 | 2
4 | val5 | desc5 | 1
5 | val6 | desc6 | 2
table2(categories)
id | name
0 | shoe
1 | glove
2 | hat
它应该返回:
articles_connected | categorie_name
3 | glove
0 | shoe
3 | hat
我认为这是一个很好的解决方案:
SELECT
COUNT(Category.id) as article_amount, Category.name
FROM
article_table as Article,
category_table as Category
WHERE
Category.id = Article.cat_id
GROUP BY
Category.id
但我的代码不正确。此SQL查询不会计入零指数 它只计算大于0的值。如何更改以下查询以计算0' d索引?
SELECT
COUNT(Category.id) as articles_connected, Category.name
FROM
arcticle as Article,
categories as Category
WHERE
Category.id = arcticle .categorie
GROUP BY
Category.id
答案 0 :(得分:1)
如果我理解正确,你没有穿鞋,但想在你的结果中显示shoes = 0(所以我忽略了你的例子中table1的最后一列)。
如果您与table2一起加入,则不会匹配,因此鞋子不在您的结果查询中。 因此,在这种情况下,您可以使用左外连接:
SELECT
COUNT(Article.id) as articles_connected, Category.name
FROM categories as Category
left outer join arcticle as Article on Category.id = arcticle .categorie
GROUP BY
Category.id
所以你得到所有文章的计数,无论它们是否在table1