status_tb
+----+----------+-------------+----------+
| 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我应该用来检索这些值并以上述格式输入它们...
答案 0 :(得分:1)
您可以简单地使用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