简体   繁体   中英

How to Use a Subquery in MySQL in the Where clause that is an argument to an OR operator?

I am trying to filter a table for specific markets by using a subquery. I want to include all null values and exclude the markets that are included in the subquery.

SELECT l.market
FROM lease
WHERE l.market != ANY(SELECT market FROM market_cte) OR l.market IS NULL

This query isn't filtering out the markets I want to get rid of.

SELECT l.market
FROM lease
WHERE l.market NOT IN (SELECT id FROM market_cte) OR l.market IS NULL

And this created a SQL compilation error.

When I list the markets I want to exclude individually, the query works but I am trying to make it more dynamic.

SELECT l.market
FROM lease
WHERE l.market NOT IN (1,2,3) OR l.market IS NULL

I would just use not exists :

select market
from lease l
where not exists (select 1 from market_cte c where c.id = l.market)

Note that this will allow records where market is null (since, in this case, c.id = l.market will never be fullfilled).

Another option is to use the left join antipattern:

select l.market
from lease l
left join market_cte c on c.id = l.market
where c.id is null

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