简体   繁体   中英

MySQL Get rows that do not match with certain conditions

It seems simple in my head but I am at a loss for getting the results I need.

My table

id, code, type
 1  1111   1
 2  1111   2
 3  1222   1 <--- This one
 4  1333   1
 5  1333   2
 6  1444   3 <--- Different type then the others

I want the output of the one that doesn't have a matching code with type 2 but only look for ones with type 1 or type 2 (if that makes sense)

id, code, type
 3  1222   1

NOTE: I have over 1 million records to query so I need something fast.

My SqlFiddle

Thanks in advance.

SELECT * FROM codes NATURAL JOIN (
  SELECT   code
  FROM     codes
  WHERE    type IN (1,2)
  GROUP BY code
  HAVING   COUNT(DISTINCT type) = 1
) t

See it on sqlfiddle .

Here is a solution using not exists :

SELECT c.*
FROM codes c
WHERE c.type = 1 and
      not exists (select 1
                  from codes c2
                  where c2.code = c.code and
                        c2.type = 2
                 )

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