gpt4 book ai didi

mysql - 如何获得mysql中两个表之间的比较差异列值

转载 作者:搜寻专家 更新时间:2023-10-30 23:28:14 25 4
gpt4 key购买 nike

状态待定

+----+----------+-------------+----------+
| id | status | description | state_id |
+----+----------+-------------+----------+
| 1 | new | north | 1 |
| 2 | assign | south | 2 |
| 3 |Postponed | east | 2 |
| 4 | Fixed | west | 3 |
| 8 | Verified | north-east | 1 |
| 9 | Closed | south-west | 2 |
| 35 | Test | South-test | 4 |
+----+----------+-------------+----------+

status_backup_tb

+----------+----+----------+-------------+----------+
|backup_id | id | status | description | state_id |
+----------+----+----------+-------------+----------+
| 1 | 1 |new | north | 1 |
| 2 | 2 |assign | south | 2 |
| 3 | 3 |Postponed | east | 2 |
| 4 | 4 | Fixed | west | 3 |
| 5 | 8 | Verified | north-east | 1 |
| 6 | 9 | Closed | south-west | 2 |
| 7 | 35| Rejected | Testing | 4 |
+----------+----+----------+-------------+----------+

想要的结果:仅 Column_changed、old_value 和 new_value

 |new_id | id |Column_changed| Old_value   |New_value |
+-------+----+--------------+-------------+----------+
|1 | 35 | status | Test | Rejected |
|2 | 35 |description | South-test | Testing |
+-------+----+--------------+-------------+----------+

如果 state_idstatus 发生了变化,我想获取 id、status 和 state_id 列及其旧值和新值.

已经尝试过但没有用

SELECT MIN(TableName) as TableName, ID, COL1, COL2, COL3 ...
FROM
(
SELECT 'Table A' as TableName, A.ID, A.COL1, A.COL2, A.COL3, ...
FROM A
UNION ALL
SELECT 'Table B' as TableName, B.ID, B.COL1, B.COl2, B.COL3, ...
FROM B
) tmp
GROUP BY ID, COL1, COL2, COL3 ...
HAVING COUNT(*) = 1
ORDER BY ID

最佳答案

一种方法是在单个 Select 查询中获取各个字段的所有更改。最终 Union 这些多个查询的结果。

我们使用 id 和相应列值不匹配的条件在两个表之间JOIN

(SELECT 
s.id,
'status' AS Column_changed,
s.status AS Old_value,
b.status AS New_value
FROM status_tb AS s
JOIN status_backup_tb AS b
ON b.id = s.id AND
b.status <> s.status)

UNION ALL

(SELECT
s.id,
'description' AS Column_changed,
s.description AS Old_value,
b.description AS New_value
FROM status_tb AS s
JOIN status_backup_tb AS b
ON b.id = s.id AND
b.description <> s.description)

UNION ALL

(SELECT
s.id,
'state_id' AS Column_changed,
s.state_id AS Old_value,
b.state_id AS New_value
FROM status_tb AS s
JOIN status_backup_tb AS b
ON b.id = s.id AND
b.state_id <> s.state_id)

ORDER BY id

关于mysql - 如何获得mysql中两个表之间的比较差异列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53400058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com