A
A
apptimeru2015-12-10 23:49:10
MySQL
apptimeru, 2015-12-10 23:49:10

Count number of rows under different conditions in one query?

Hello everyone, please tell me there is a table with comments, you need to combine 2 such simple queries into one:

SELECT COUNT(id) as one_count FROM comments WHERE user_id = $user_id AND post_id != 1

SELECT COUNT(id) as two_count FROM comments WHERE user_id = $user_id AND post_id = 1

those. You need to know how many comments in total from a specific user, minus the comments on a specific post, and you also need to know how many comments specifically for this post.
And in general, if it makes sense to combine all this into one query for optimization purposes?
Many thanks in advance to all for the help.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Bezymyannikov, 2015-12-11
@psman

SELECT COUNT(id) as `count`, "one" as `name` FROM comments WHERE user_id = $user_id AND post_id != 1
UNION
SELECT COUNT(id) as `count`, "two" as `name` FROM comments WHERE user_id = $user_id AND post_id = 1
count | name
=============
12 | one
234 | two

N
nelson, 2015-12-11
@nelson

SELECT 
SUM( IF(post_id != 1, 1, 0) ) as one_count,  
SUM( IF(post_id = 1, 1, 0) ) as two_count
FROM comments 
WHERE user_id = $user_id

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question