简体   繁体   English

如何在作为 OR 运算符参数的 Where 子句中使用 MySQL 中的子查询?

[英]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.这造成了 SQL 编译错误。

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 :我只会使用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).请注意,这将允许marketnull记录(因为在这种情况下, c.id = l.market永远不会被c.id = l.market )。

Another option is to use the left join antipattern:另一种选择是使用left join反模式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM