简体   繁体   中英

Select all rows that do NOT match in MySQL query

I would like to get as result all rows from the table except the rows inside the query. Update: The rows need to be added or removed from the result set on basis of the three properties makeModelDescription, firstRegistration and mileage. Only if all three values match the row should not be part of the result set. The WHERE clause will contain up to 20 conditions. Therefore I tried

SELECT * 
FROM cars 
WHERE (makeModelDescription<>'Seat Arosa 2.0 Stella' AND 
       firstRegistration='EZ 03/2005' AND mileage='101.000 km') OR 
      (makeModelDescription<>'Seat Arosa 3.0 Stella' AND 
       firstRegistration='EZ 03/2005' AND mileage='101.000 km')

with a sample table:

在此处输入图片说明

But instead of getting the expected result:

  • BMW X5 4.4 i aus erster Hand
  • Corvette C5 Cabrio Seat
  • Arosa 4.0 Stella

I got the result:

在此处输入图片说明

Can anybody with more experience please support and help to formulate the correct query.

In fact, you are doing this with your SELECT :

SELECT * 
FROM cars 
WHERE firstRegistration='EZ 03/2005' AND mileage='101.000 km'

since you put a OR between both models.

So, you just need to look if they are different than the models that you are refering to :

SELECT * 
FROM cars 
WHERE (makeModelDescription <>'Seat Arosa 2.0 Stella' AND 
       makeModelDescription <>'Seat Arosa 3.0 Stella')

EDITED :

SELECT * 
FROM cars 
WHERE (makeModelDescription <>'Seat Arosa 2.0 Stella' AND 
       makeModelDescription <>'Seat Arosa 3.0 Stella')  OR 
        firstRegistration <>'EZ 03/2005' OR
        mileage<>'101.000 km'

Your WHERE condition is logically wrong,

(
    makeModelDescription<>'Seat Arosa 2.0 Stella' 
    AND firstRegistration='EZ 03/2005' 
    AND mileage='101.000 km'
)

    OR 

(
    makeModelDescription<>'Seat Arosa 3.0 Stella' 
    AND firstRegistration='EZ 03/2005' 
    AND mileage='101.000 km'
)

Here what happens now is, both conditions becomes true when the firstRegistration becomes equal to EZ 03/2005 (and also if mileage becomes equal to 101.000km ). What you should do is only omit the records where makeModelDescription is equal to Seat Arosa 2.0 Stella OR Seat Arosa 3.0 Stella . So your query should be like below,

SELECT * 
FROM cars 
WHERE 
makeModelDescription <>'Seat Arosa 2.0 Stella'
AND 
makeModelDescription <>'Seat Arosa 3.0 Stella'

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