2016-12-31 87 views
0

我有一個表教練。表教練都有數據是這樣的:如何在mysql中更新多行?

enter image description here

我想更新player_id列,因此該數據是這樣的:

enter image description here

具有type =「教練」 Player_id值從取type =「player」的id的值。這是採取基於字段信息與現場碼值player_code之間的關係

我使用查詢自己試圖加入更新這樣的:

UPDATE coach 
SET player_id = (
      SELECT b.id 
      FROM coach a 
      LEFT JOIN coach b ON REPLACE(JSON_EXTRACT(b.information, "$.player_code"), '"', '') = b.code 
      WHERE b.`type` = 'player' 
     ) 
WHERE `type` = 'coach' 

當被執行查詢,存在錯誤像這樣:

Error Code: 1093 
You can't specify target table 'coach' for update in FROM clause 

有沒有人可以幫助我?

回答

1
update coach as c1 
inner join (
    select b.id, 
     b.code 
    from coach b 
    where b.`type` = 'player' 
    ) as c2 on REPLACE(JSON_EXTRACT(c1.information, '$.player_code'), '"', '') = c2.code 

set c1.player_id = c2.id 
where c1.type = 'coach'; 
+1

太好了。有用。謝謝 –