gpt4 book ai didi

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 |
| 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 |
| 7 | 35| Rejected | Testing | 4 |
+----------+----+----------+-------------+----------+

从生成的 mysql 中获得输入结果后,我需要将这些结果插入到另一个表 (audit_status_tb),如下所示...如何实现?

这里是获取我需要的记录的sql

(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)

audit_status_tb

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

我不确定哪种插入选择?我应该使用 mysql 来检索这些值并以上述格式输入它们...

最佳答案

您可以简单地使用 Insert Into .. Select声明:

INSERT INTO audit_status_tb (id, Column_changed, Old_value, New_value) 

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

关于mysql - 如何将两个表之间的比较记录结果插入到另一个表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53412101/

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