比较(可能)来自2个表的多个值

时间:2017-09-07 20:07:03

标签: mysql join where

我需要显示两个表中没有相同精确值的行,并且只显示不同的行。举例说明:

表1

Item_col      val_col
 Item1          1a
 Item1          1b
 Item1          2a
 Item2          2b
 Item2          2a
 Item3          1a   

表2

Item_col       val_col
 Item1          1b
 Item2          2b
 Item2          2a
 Item3          1b
 Item3          1a
 Item3          2a

预期结果:

Item_col       val_col
 Item1          1a
 Item1          2a
 Item3          1b
 Item           2a

在上面的示例中,结果过滤掉了具有相同Item_col和val_col信息的行。我已经使用了连接和where子句的组合,但我没有得到我需要的结果。在此先感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

我认为你正在寻找这样的东西 - 我认为代码非常明显:

SELECT  *
FROM    table1 t1
WHERE   NOT EXISTS ( SELECT 1
                     FROM   table2 t2
                     WHERE  t2.Item_Col = t1.Item_Col
                            AND t1.val_col = t2.val_col )
UNION
SELECT  *
FROM    table2 t2
WHERE   NOT EXISTS ( SELECT 1
                     FROM   table1 t1
                     WHERE  t2.Item_Col = t1.Item_Col
                            AND t1.val_col = t2.val_col );

这是展示它的add them as references

答案 1 :(得分:0)

我会这样做。

SELECT t1.*
FROM table1 t1
LEFT JOIN table2 t2 ON t1.Item_col = t2.Item_col AND t1.val_col = t2.val_col
WHERE t2.Item_col IS NULL

UNION ALL

SELECT t2.*
FROM table2 t2
LEFT JOIN table1 t1 ON t1.Item_col = t2.Item_col AND t1.val_col = t2.val_col
WHERE t1.Item_col IS NULL