简体   繁体   English

在NOT IN中使用UNION

[英]Using UNION inside of NOT IN

I'm trying to make query using a NOT IN condition. 我正在尝试使用NOT IN条件进行查询。 If I use a subquery I got no problem, but when I try to use UNION to join results from two tables, I got an error. 如果我使用子查询我没有问题,但是当我尝试使用UNION连接两个表的结果时,我收到了一个错误。

This is what I'm doing: 这就是我正在做的事情:

SELECT *
FROM users
WHERE id NOT IN( 
    (
        SELECT DISTINCT(user_id) AS id
        FROM users_table_1
    )
    UNION
    (
        SELECT DISTINCT(user_id) AS id
        FROM users_table_2
    )   
)

Is there a way to get what I want using subqueries? 有没有办法通过子查询获得我想要的东西?

I think there's a syntax issue in your code. 我认为您的代码中存在语法问题。 Did you try to put UNION inside the subquery? 你试图将UNION 放在子查询中吗?

SELECT *
FROM users
WHERE id NOT IN( 
        SELECT user_id AS id
        FROM users_table_1
        UNION
        SELECT user_id
        FROM users_table_2 
)

The DISTINCT keyword is redundant (see @ypercube's comment). DISTINCT关键字是多余的(请参阅@ ypercube的评论)。

@yasir Actually, this is not a real syntax problem (the same syntax is accepted by other SQL databases), but rather a limitation in MySQL query parser, implemented using the bison parser generator . @yasir实际上,这不是一个真正的语法问题(其他SQL数据库接受相同的语法),而是使用bison解析器生成器实现的 MySQL查询解析器的限制。

The error stems from the parser's need to decide between two possible parse trees, since both SELECT subqueries and sub-expressions may be enclosed in parentheses. 该错误源于解析器需要在两个可能的解析树之间进行决策,因为SELECT子查询和子表达式都可以括在括号中。 Therefore a minimal solution here would be to remove the parens only from the first subquery, ie: 因此,这里的最小解决方案是仅从第一个子查询中删除parens,即:

SELECT *
FROM users
WHERE id NOT IN( 
    SELECT user_id AS id
    FROM users_table_1
    UNION
    (
        SELECT user_id
        FROM users_table_2
    )
)

This way you "help" mysql disambiguate between the two possible parse trees. 这样你就可以“帮助”mysql消除两个可能的解析树之间的歧义。 In bison lingo, that would avoid the shift/reduce conflict. 在野牛术语中,这将避免转移/减少冲突。

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

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