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

标签 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 |
+----------+-------+

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

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

最佳答案

另一种替代方法是使用 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 不支持该连接,并且必须使用 进行模拟LEFT JOINRIGHT 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

Demo on dbfiddle

关于mysql - 有没有更好的方法来获取具有相同字段的两个表之间的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54780660/

相关文章:

php - 如何在pdo准备语句中用空格写列名

mysql - 优化此 sql 查询的最佳方法是什么

mysql - 在查找中使用列约束时未加载关系

mysql - 这些sql查询之间的区别

MySql 的列数和参数大小对性能的影响

php - 如何通过电子邮件发送数据库中的一长串电子邮件?

php - 如何用php在两列中显示数据

php - mysql按字母顺序排序,最后设置 "other"

php - Php 中的登录脚本

c++ - 为每个查询初始化到 MYSQL 的连接有多糟糕?