简体   繁体   中英

Using UNION inside of NOT IN

I'm trying to make query using a NOT IN condition. 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.

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?

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).

@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 .

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. Therefore a minimal solution here would be to remove the parens only from the first subquery, ie:

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. In bison lingo, that would avoid the shift/reduce conflict.

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