[英]MySQL how to update table data from another table? 1 row in table A maps to 2 rows in table B
我有表A,三列
id text1 text2
我有表B,四列
id A_id key value
表B中的數據看起來像
id A_id key value
1 1 text1 test_value1
2 1 text2 test_value2
表A中的每一行都映射到表B中的2行。表A中的text1和text2列現在為空。 我正在嘗試將數據從表B復制到表A。
我該如何一步一步做到這一點? 謝謝。 現在我有以下聲明,但必須指定
AND B.key = "text1"
,如何同時更新text1和text2列?
UPDATE A
INNER JOIN B
ON A.id = B.A_id
AND B.key = "text1"
SET A.text1 = B.value
加入B
兩次,每個“鍵”一次。
UPDATE `A`
INNER JOIN `B` `B1`
ON `B1`.`A_id` = `A`.`id`
AND `B1`.`key` = 'text1'
INNER JOIN `B` `B2`
ON `B2`.`A_id` = `A`.`id`
AND `B2`.`key` = 'text2'
SET `A`.`text1` = `B1`.`value`,
`A`.`text2` = `B2`.`value`;
這是簡單的步驟,可能會解決您的問題。
create table tab_b(id int,
A_id int,
`key` varchar(20),
`value` varchar(20));
insert into tab_b values
(1,1,'text1','test_value1'),
(2,1,'text2','test_value2');
create table tab_a(id int,text1 varchar(20),text2 varchar(20));
insert into tab_a(id,text1,text2)
select id,max(text1) text1,max(text2) text2
from(
select a_id as id,
case when `key`='text1' then `value` end text1,
case when `key`='text2' then `value` end text2
from tab_b) a;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.