我有一个 sql 查询问题。我不想为相同的结果执行三次查询。
在我的表中,我有一个字段req_type
,它有三个参数,
要么 1,要么 2,要么 3。
我希望在一个查询中基于 req_type 进行计数器,而不是像下面这样执行查询 3 次
select count(id) as premium FROM tablename where req_type=1
select count(id) as premium1 FROm tablename where req_type=2
select count(id) as premium2 FROm tablename where req_type=3
我被困住了,有人可以帮助我吗?
最佳答案
您可以使用case
来进行此类计数
select sum(case when req_type=1 then 1 else 0 end) as premium,
sum(case when req_type=2 then 1 else 0 end) as premium1,
sum(case when req_type=3 then 1 else 0 end) as premium2
FROM tablename
关于mysql - req_type 在一个查询中明智地计数 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48200907/