MySQL单向比较没有主键的两个表

时间:2016-01-30 06:12:58

标签: mysql comparison

我有两张桌子。他们没有主键或唯一列。它们具有相同的列数。

+---------------+  
|    table_1    |  
+---------------+  
| a | b | c | d |  
+---+---+---+---+  
| 1 | 1 | 1 | 1 |  
+---+---+---+---+  
| 1 | 3 | 1 | 1 |  
+---+---+---+---+ 

+---------------+
|    table_2    |
+---------------+
| a | b | c | d |
+---+---+---+---+
| 1 | 1 | 1 | 1 |
+---+---+---+---+
| 1 | 2 | 1 | 1 |
+---+---+---+---+

我希望通过比较所有字段来获取table_1中不存在的数据。

我的查询如下所示,但它返回两个表中都没有的所有记录。

SELECT a, b, c, d
FROM
(
    SELECT t1.a, t1.b, t1.c, t1.d
    FROM table_1 as t1
    UNION ALL
    SELECT t2.a, t2.b, t2.c, t2.d
    FROM table_2 as t2
)  t
GROUP BY a, b, c, d
HAVING COUNT(*) = 1
ORDER BY a

+----------------+
|        t       |
+----------------+
| id | a | b | c |
+----+---+---+---+
|  1 | 2 | 1 | 1 |
+----+---+---+---+
|  1 | 3 | 1 | 1 |
+----+---+---+---+

我想要的结果就是这个。

+----------------+
|        t       |
+----------------+
| id | a | b | c |
+----+---+---+---+
|  1 | 2 | 1 | 1 |
+----+---+---+---+

2 个答案:

答案 0 :(得分:1)

您正在查找两个表中每个表都唯一的记录集。实现此目的的一种方法是UNION一起查询两个LEFT JOIN查询,这些查询获取表之间不常见的记录。

SELECT t1.a, t1.b, t1.c, t1.d
FROM table_1 t1
LEFT JOIN table_2 t2
    ON t1.a = t2.a AND t1.b = t2.b AND t1.c = t2.c AND t1.d = t2.d
WHERE t2.a IS NULL
UNION ALL
SELECT t2.a, t2.b, t2.c, t2.d
FROM table_2 t2
LEFT JOIN table_1 t1
    ON t1.a = t2.a AND t1.b = t2.b AND t1.c = t2.c AND t1.d = t2.d
WHERE t1.a IS NULL

按照以下链接进行正在运行的演示:

SQLFiddle

答案 1 :(得分:0)

如果您尝试获取第二行中不存在的行,则可以使用此类查询

    SELECT * FROM A WHERE NOT 

      EXIST (SELECT * FROM B WHERE
      A.field1 = B.field1