S
S
Sergey2017-10-04 09:03:41
MySQL
Sergey, 2017-10-04 09:03:41

How to make a selection from the MySql database by condition - only if all records have such a value?

There is a table "order":
id | status_id | user_id
1 | 0 | 1
2 | 1 | 1
3 | 0 | 2
4 | 0 | 2
5 | 0 | 3
6 | 1 | 4
It is necessary to display all user_id who have ALL orders with status 0, that is, the result should be:
2 and 3
Or only with status 1, then the result should be:
4

Answer the question

In order to leave comments, you need to log in

4 answer(s)
R
RidgeA, 2017-10-04
@RidgeA

Simple, but most likely not the best option.

SELECT * FROM table GROUP BY user_id HAVING SUM (status_id) = 0

M
Mikhail Grigoriev, 2017-10-04
@Sleuthhound

gospidi: or
select user_id from order where status_id = '1';

A
Andrew, 2017-10-04
@sAndreas

SELECT user_id FROM table
GROUP BY user_id
HAVING SUM (ABS(status_id)) -COUNT(status_id)=0
or
HAVING SUM (ABS(status_id)) = COUNT(status_id) will output
2,3,4

N
nozzy, 2017-10-04
@nozzy

Something like this:

select 
distinct
t1.user_id
from table t1
left join 
 (select distinct 
  user_id 
  from table 
  where status_id <> 0
 ) t2 on t2.user_id = t1.user_id
where t1.status_id = 0
and t2.user_id is null

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question