Codeigniter:来自一个表的多个COUNT和SUM


Codeigniter: multiple COUNT and SUM from one table

我有MySQL表如下:

id | ads | status | user_id |

最好的方法是:

  1. where user_id=1 and status=1
  2. 所有行的计数
  3. 所有行数where user_id=1 and status=0
  4. where user_id=0 所有广告之和
  5. 所有广告where user_id=1之和

我的问题:我可以只运行一个查询来获得所有4个结果吗?如果有,请解释一下。

提前感谢。

试试这个:

select sum(if(status=1 and user_id=X, 1, 0)) as V1,
sum(if(status=1 and user_id=X, ads, 0)) as V2,
sum(if(status=0 and user_id=X, 1, 0)) as V3,
sum(if(status=0 and user_id=X, ads, 0)) as V4
FROM table)