将多个行从一个表更新到另一个表

时间:2016-02-21 20:04:01

标签: mysql

我正在尝试将多个行从一个表更新到另一个表。

我有这个有效但我需要在一个查询中更新8个值而不是8个单独的查询。

我需要这个

slot_id  |  spell_id
--------------------
0    |  1518
1    |  1519
2    |  1522
3    |  3476
4    |  4881
6    |  3475
7    |  4880

到这个

spell1 | spell2 | spell3 | spell4 | spell5 | spell6 | spell7 | spell8
---------------------------------------------------------------------
   0   |   0    |   0    |    0   |   0    |     0  |   0    |    0

我所取得的成就是一次一个。

UPDATE instance_saved_info
INNER JOIN character_memmed_spells ON instance_saved_info.id = character_memmed_spells.id
SET instance_saved_info.Spell1 = character_memmed_spells.spell_id
WHERE character_memmed_spells.slot_id = 0

我需要添加以使其正常工作。

SET instance_saved_info.Spell2 = character_memmed_spells.spell_id
WHERE character_memmed_spells.slot_id = 1
SET instance_saved_info.Spell3 = character_memmed_spells.spell_id
WHERE character_memmed_spells.slot_id = 2
SET instance_saved_info.Spell4 = character_memmed_spells.spell_id
WHERE character_memmed_spells.slot_id = 3
SET instance_saved_info.Spell5 = character_memmed_spells.spell_id
WHERE character_memmed_spells.slot_id = 4
SET instance_saved_info.Spell6 = character_memmed_spells.spell_id
WHERE character_memmed_spells.slot_id = 5
SET instance_saved_info.Spell7 = character_memmed_spells.spell_id
WHERE character_memmed_spells.slot_id = 6
SET instance_saved_info.Spell8 = character_memmed_spells.spell_id
WHERE character_memmed_spells.slot_id = 7

谢谢

2 个答案:

答案 0 :(得分:1)

您可以声明多个$url = 'https://api.sandbox.paypal.com/v1/oauth2/token'; $header_array = array( 'Accept: application/json', 'Accept-Language: en_US', ); $username = 'EOJ2S-Z6OoN_le_KS1d75wsZ6y0SFdVsY9183IvxFyZp'; $password = 'EClusMEUk8e9ihI7ZdVLF5cZ6y0SFdVsY9183IvxFyZp'; $data_string = 'grant_type=client_credentials'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($ch, CURLOPT_TIMEOUT, 5); curl_setopt($ch, CURLOPT_HTTPHEADER, $header_array); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password); $data = curl_exec($ch); curl_close($ch); var_dump($data); 运算符

SET

答案 1 :(得分:0)

假设我正确理解了您的问题,您可以使用conditional aggregationpivot update所需的8个字段的子查询:

UPDATE instance_saved_info i
INNER JOIN (
    SELECT id, 
           max(case when slot_id = 0 then spell_id end) slot0,
           max(case when slot_id = 1 then spell_id end) slot1,
           ....
           max(case when slot_id = 7 then spell_id end) slot7
    FROM character_memmed_spells 
    GROUP BY id) c ON i.id = c.id
SET i.Spell1 = c.slot0, i.Spell2 = c.slot1, ..., i.Spell8 = c.slot7