Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/243.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php mysql左连接计数始终返回1_Php_Mysql - Fatal编程技术网

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