这是我的mysql查询。当我传入逗号分隔的id
时,我需要获取id和count值SELECT tag_id AS id, COUNT( tag_id ) AS count FROM tag WHERE tag_id IN ( 1, 2, 3, 28 );
我得到了
---------------
| id | count |
---------------
| 1 | 4 |
---------------
预期结果是:
----------------
| id | count |
----------------
| 1 | 2 |
| 2 | 1 |
| 3 | 5 |
| 28 | 0 |
----------------
请帮助......
答案 0 :(得分:1)
使用聚合函数你应该将它们分组
SELECT tag_id AS id, COUNT( tag_id ) AS count
FROM tag WHERE tag_id IN ( 1, 2, 3, 28 )
GROUP BY tag_id ;
答案 1 :(得分:1)
您需要group by
声明:
SELECT tag_id AS id, COUNT( tag_id ) AS count
FROM tag
WHERE tag_id IN ( 1, 2, 3, 28 )
GROUP BY tag_id;
您的查询是一个没有group by
的聚合查询,因此它会返回一行(将所有行视为一个组)。
接下来,如果要返回0的计数,则需要以不同的方式构建查询。这是使用left join
的版本:
select ids.id, count(t.tag_id) as cnt
from (select 1 as id union all
select 2 union all
select 3 union all
select 28
) ids left join
tag t
on t.tag_id = ids.id
group by ids.id;