首页 > 解决方案 > 请求Select时如何计算列表中的条目数?

问题描述

对于演示文稿中可能存在的错误,我深表歉意,我使用了翻译。假设有一个用户表,其中有一个 id 字段。并且有一个列表列出了 id 编号,其中一些是重复的。我的查询

select id, count(*)
from users
where id in (3, 10, 10, 10)
group by id;

返回以下 3 - 1、10 - 1。我想得到 3 - 1、10 - 3,依此类推。有没有可能以某种方式得到它?UPD。列表中的数据 (3, 10, 10, 10) 只是一个示例,确切的位数未知,因为它们是从另一个问题返回的。

标签: mysqlsqlcount

解决方案


您将需要使用join. 为此,您可以将值放在派生表中:

select id, count(*)
from users u join
     (select 3 as id union all
      select 10 as id union all
      select 10 as id union all
      select 10 as id union all
     ) i
     using(id)
group by id;

推荐阅读