如何在执行左连接之前排除某些记录

时间:2014-05-29 21:42:13

标签: mysql sql left-join

我正在寻找一种在左连接执行之前排除某些记录的方法。

我的sql语句如下所示:

SELECT * FROM users 
LEFT JOIN (SELECT * FROM premissions WHERE post_id = 1) AS p
ON p.user_id = users.id
WHERE p.id IS NULL

如何在用户表中排除id为1和2的记录?

4 个答案:

答案 0 :(得分:0)

使用子选择

SELECT * FROM
(select * from users where id not in(1,2))
 u 
LEFT JOIN (SELECT * FROM premissions WHERE post_id = 1) AS p
ON p.user_id = u.id
WHERE p.id IS NULL

答案 1 :(得分:0)

您可以为WHERE子句添加条件:

SELECT  *
FROM    users
LEFT JOIN ( SELECT  *
            FROM    premissions
            WHERE   post_id = 1
           ) AS p 
    ON p.user_id = users.id
WHERE   p.id IS NULL
  AND users.id NOT IN (1,2)

答案 2 :(得分:0)

SELECT * FROM 
(select from users where id not in (1,2)) u
LEFT JOIN (SELECT * FROM premissions WHERE post_id = 1) AS p
ON p.user_id = u.id
WHERE p.id IS NULL

答案 3 :(得分:0)

你可以尝试过滤where子句,或者像M Khalid Junaid所提到的那样进行过滤。

SELECT * FROM users 
LEFT JOIN (SELECT * FROM premissions WHERE post_id = 1) AS p
ON p.user_id = users.id
WHERE p.id IS NULL
 and users.id not in (1, 2)