0

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.

3
  • And how do you want to do it? why codeigniter, do you want to do it with Active Record? Commented Mar 20, 2014 at 23:00
  • Actually it can be regular MySQL query; disregard CI. Also I can get results by running 2 queries: one for condition: status=1; another query when status=0 ... But wonder if all of that can be done by running one single query. Commented Mar 20, 2014 at 23:06
  • Well, I thought it better, maybe with the query below you can do it, :P Commented Mar 20, 2014 at 23:07

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

XD, I see, I had to put all with sum, :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.