简体   繁体   中英

Codeigniter: multiple COUNT and SUM from one table

I have MySQL table as follow:

id | ads | status | user_id |

What would be best way to get:

  1. count of all rows where user_id=1 and status=1
  2. count of all rows where user_id=1 and status=0
  3. sum of all ads where user_id=0
  4. sum of all ads where user_id=1

My question: Can I run only one query to get all 4 results? If so, would you please explain how.

Thank you in advance.

Try this:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM