有没有更好的方法来获取具有相同字段的两个表之间的差异?

时间:2019-02-20 07:07:27

标签: mysql

我有两个表格,如下所示:

table1:

+----+----------+-------+
| id | order_id | price |
+----+----------+-------+
|  1 |     1024 |    20 |
|  2 |     1025 |    30 |
|  3 |     1026 |    35 |
|  4 |     1027 |    45 |
+----+----------+-------+

table2

+----+----------+-------+------+
| id | order_id | price | name |
+----+----------+-------+------+
|  1 |     1024 |    20 | a    |
|  2 |     1025 |    30 | b    |
|  3 |     1026 |    35 | c    |
|  4 |     1027 |    40 | d    |
+----+----------+-------+------+

我想做的只是对字段order_idprice进行露营,并在order_id = 1027时获得不同的内容


这是我的拙见:


SELECT * FROM (

SELECT order_id, price FROM table1 

UNION ALL

SELECT order_id, price FROM table2

) t

GROUP BY order_id, price 

HAVING COUNT(*) = 1


# result 

+----------+-------+
| order_id | price |
+----------+-------+
|     1027 |    40 |
|     1027 |    45 |
+----------+-------+

有没有更好的方法来获取它。

任何评论都非常受欢迎。非常感谢。

2 个答案:

答案 0 :(得分:1)

另一种替代方法是使用JOIN查找不匹配的价格:

SELECT t1.order_id, t1.price AS table1_price, t2.price AS table2_price
FROM table1 t1
JOIN table2 t2 ON t2.order_id = t1.order_id AND t2.price != t1.price

输出:

order_id    table1_price    table2_price
1027        45              40

Demo on dbfiddle

如果您还想捕获一个表中存在的行,而不是另一个表中的行,那么您将需要一个FULL OUTER JOIN,这是MySQL不支持的,并且必须使用UNION来模拟LEFT JOINRIGHT JOIN

SELECT * 
FROM (SELECT t1.order_id AS order_id, t1.price AS table1_price, t2.price AS table2_price
      FROM table1 t1
      LEFT JOIN table2 t2 ON t2.order_id = t1.order_id
      UNION
      SELECT t2.order_id, t1.price AS table1_price, t2.price AS table2_price
      FROM table1 t1
      RIGHT JOIN table2 t2 ON t2.order_id = t1.order_id) t
WHERE table1_price != table2_price OR
      table1_price IS NULL OR
      table2_price IS NULL

输出:

order_id    table1_price    table2_price
1027        45              40
1028        50              null
1029        null            45

Demo on dbfiddle

答案 1 :(得分:0)

您可以使用左联接获取值

SELECT table1.order_id, table1.price FROM table1 LEFT JOIN table2 ON table2.order_id = table1.order_id AND table2.price != table1.price