O
O
Oleg Karnaukhov2016-01-07 05:48:01
MySQL
Oleg Karnaukhov, 2016-01-07 05:48:01

How to exclude all rows with the same field value if one of them doesn't match?

For example, there is a table
id | objid | status
1 | 1 | 1
2 | 1 | 0
3 | 1 | 0
4 | 1 | 1
5 | 2 | 0
6 | 2 | 0
7 | 2 | 0
8 | 2 | 0
9 | 3 | 1
10 | 3 | 1
In this case, I only need objid = 2 because all values ​​have status=0. At the same time, objid 1 and 3 are not suitable, because for 3 status=1 and for 1 the status is 1 for some, and 0 for some.
Yes, in theory, you can take those that are equal to 1 and exclude these IDs from the sample. But let's imagine that there are about 100 thousand such records from 1, and it will be expensive to exclude them in a subquery.
Is it possible to tell mysql not to need all objid where status is not 0? Or, to rephrase, exclude all objids if they have at least one value equal to 1?
Let's even assume that we got a list of those where there is at least one zero - how to remove from this list all entries with the same objid where there is at least one unit?
PS. Statuses can be not 2 but more. For example 5 statuses. You need to get those objid where there is status 0 and 4 but no status 1 2 and 3.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Stalker_RED, 2016-01-07
@Stalker_RED

Clumsy, but it works
sqlfiddle.com/#!9/cb6ea/1
Another option
sqlfiddle.com/#!9/cb6ea/2
Or even like this:
sqlfiddle.com/#!9/cb6ea/3
For good, you need to look explain, think and/or test against the data, but I'll leave that to you.

S
svd71, 2016-01-07
@svd71

Select * from mytable t1
Where not exists (select * from mytable t2
Where t2.objid=t1.objid and t2.status=1)

R
Rsa97, 2016-01-07
@Rsa97

SELECT `objid`
    FROM `table`
    GROUP BY `objid`
    HAVING MAX(`status`) = 0

SELECT DISTINCT `t1`.`objid`
    FROM `table` AS `t1`
    LEFT JOIN (
        SELECT DISTINCT `objid`
            FROM `table`
            WHERE `status` = 1
    ) AS `t2` USING(`objid`)
    WHERE `t2`.`objid` IS NULL

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question