如何从mysql中删除匹配的行Join Result并显示不匹配的行?

时间:2010-08-31 10:16:19

标签: php sql mysql join

有没有办法从MySQL join Query中删除匹配的行。 实际上我有两个表,我存储了pub_id,而post_id在两个表中都是常见的。 当我查询table1中的所有匹配行时,我想要一个结果,并且不应该列出table2,并且应该仅列出不匹配的行。

2 个答案:

答案 0 :(得分:1)

查询仅存在于两个表之一中的返回行:

SELECT *
FROM Table1 t1
WHERE NOT EXISTS (Select 1 from Table2 t2 
                 Where t1.pub_id = t2.pub_id
                AND t1.post_Id = t2.post_id)
UNION ALL
SELECT *
FROM Table2 t1
WHERE NOT EXISTS (Select 1 from Table1 t2 
                 Where t1.pub_id = t2.pub_id
                AND t1.post_Id = t2.post_id)

答案 1 :(得分:0)

你需要这样的东西:

    SELECT * FROM tablea AS a
   RIGHT  JOIN tableb AS o ON a.id = o.id WHERE a.pub_id IS NULL and a.post_id is null 
UNION    
SELECT * FROM tablea AS a
   LEFT  JOIN tableb AS o ON a.id = o.id WHERE o.pub_id IS NULL and o.post_id is null