mysql左连接计数总是返回1

时间:2015-12-16 14:37:12

标签: php mysql

这是我的数据结构:

categories 
id   name
-------------------
1    category1
2    category2
3    category3


items
id    name    cat
-------------------
1     item1   1
2     item2   1
3     item3   1
4     item4   2

期望的输出:

cat   category    total_items
-----------------------------------
1     category1   3
2     category2   1
3     category3   0

我尝试了以下查询:

select categories.id as cat, 
    categories.name as category, 
    count(*) AS total_items from categories 
    left join items on categories.id = items.cat

它将永远为类别3返回1 ..任何想法有什么不对?

2 个答案:

答案 0 :(得分:5)

试试这个:

select categories.id as cat, categories.name as category, 
       count(items.cat) AS total_items 
from categories 
left join items on categories.id = items.cat

您的查询存在的问题是COUNT(*)基于行计算,包括来自NULL表的items个值字段的行。

改为使用count(items.cat),将NULL - 值字段保留。

答案 1 :(得分:0)

试试吧......

select categories.id as cat, 
    categories.name as category, 
    count(*) AS total_items from items
    left join categories on items.cat=categories.id