Php mysql左连接计数始终返回1
以下是我的数据结构:Php mysql左连接计数始终返回1,php,mysql,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 -----
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。。有什么问题吗?试试这个:
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(*)
按行计数,包括items
表中带有NULL
值字段的行
改为使用count(items.cat)
将NULL
值字段保留为空。尝试以下操作:
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(*)
按行计数,包括items
表中带有NULL
值字段的行
改为使用count(items.cat)
将NULL
值字段保留为空。试试
select categories.id as cat,
categories.name as category,
count(*) AS total_items from items
left join categories on items.cat=categories.id
试试看
select categories.id as cat,
categories.name as category,
count(*) AS total_items from items
left join categories on items.cat=categories.id