我有两个具有相同id的表,我想用第二个表中的值更改两个表的id。
例: TABLE_1
ID TITLE CONTENT AUTHOR
1 aaa abcd aaaa
2 aaa abcd aaaa
3 aaa abcd aaaa
4 aaa abcd aaaa
TABLE_2:
ID post_id post_title pos_key value
1 1 aaa a_key 2
2 1 aaa E_key 2000
3 2 aaa b_key 3
4 2 aaa b_key 3
5 2 aaa E_key 2500
6 3 aaa c_key 4
7 3 aaa d_key 5
8 3 aaa E_key 3000
9 4 aaa f_key 6
10 4 aaa E_key 3500
如何从Table_2的值更新所有Table_1 ID和Table_2 post_id,其中post_key行上有E_key?
这就是我想要的两张桌子:
TABLE_1
ID TITLE CONTENT AUTHOR
2000 aaa abcd aaaa
2500 aaa abcd aaaa
3000 aaa abcd aaaa
3500 aaa abcd aaaa
TABLE_2:
ID post_id post_title pos_key value
1 2000 aaa a_key 2
2 2000 aaa E_key 2000
3 2500 aaa b_key 3
4 2500 aaa b_key 3
5 2500 aaa E_key 2500
6 3000 aaa c_key 4
7 3000 aaa d_key 5
8 3000 aaa E_key 3000
9 3500 aaa f_key 6
10 3500 aaa E_key 3500
答案 0 :(得分:0)
你有什么尝试?一个好的开始是编写一个SELECT
查询,它同时提取旧值和新值;从那里通常很容易将其重写为UPDATE
。我相信这样做会:
UPDATE T1
SET ID = T2.Value
FROM Table_1 AS T1
INNER JOIN Table_2 AS T2 ON T1.ID = T2.post_id
WHERE
T2.pos_key = 'E_key'
UPDATE T2
SET post_id = NewIDs.Value
FROM Table_2 AS T2
INNER JOIN Table_2 AS NewIDs ON T2.post_id = NewIDs.post_id
WHERE
NewIDs.pos_key = 'E_key'
如果我的MySQL关闭,我很抱歉,我通常在MS SQL中工作。