我有两个表如下:
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_id
和price
,并在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 |
+----------+-------+
有没有更好的方法来获取它。
非常欢迎任何评论。非常感谢。
最佳答案
另一种替代方法是使用 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
如果您还想捕获一个表中存在但另一个表中不存在的行,那么您将需要一个 FULL OUTER JOIN
,MySQL 不支持该连接,并且必须使用 进行模拟
:LEFT JOIN
和 RIGHT JOIN
的 code>UNION
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
关于mysql - 有没有更好的方法来获取具有相同字段的两个表之间的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54780660/