2015-12-16 31 views
1

这里是我的数据结构:MySQL的左连接数始终返回1

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 

,并总是返回1为类别3 ..任何想法有什么不对?

回答

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(*)数行的基础上,包括从itemsNULL -valued字段行。

改为使用count(items.cat),将NULL置为值。

0

尝试...

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