[英]MySQL update with data from two tables
我有一個MySQL數據庫,其中有兩個表需要修改。 第一張桌子上有筆記
id type note
1 1 24 months warranty
2 1 12 months warranty
3 2 Garage in Denver
4 3 Pre sales maintenance done
....
然后是一個載有許多載具表的載具表,以及一個用文字而非指針保存注釋的字段
id licence_plate ... sales_notes ...
1 XH34DN ... <warranty>24 months warranty</warranty><garage>Garage in Denver</garage><maintenance>Pre sales maintenance done</maintenance> ...
2 K4B3C6 ... <warranty>12 months warranty</warranty><garage>Garage in Sacramento</garage><maintenance>Pre sales maintenance not done</maintenance> ...
可以想象,這是高效率的,我想修改為保存便箋ID的指針。
id licence_plate ... warranty_note garage_note maintenace_note ...
1 XH34DN ... 1 3 4 ...
2 K4B3C6 ... 2 7 12 ...
我可以手動更新,但我想構建一個可以按類型自動更新的工具。
因此,對於notes.type = 1而言,如果在vehicle.sales_notes中找到notes.note文本,則會更新vehicle.warranty_note。
任何想法如何建立這樣的東西?
我有這樣的想法,但是id不起作用。 沒有結果更新
UPDATE tx_vehicle v, tx_note n
SET v.garage_note = n.uid
WHERE v.sales_notes LIKE ('%'+n.note+'%')
MySQL具有特殊的XML解析功能 。
insert into your_new_notes_table (id, licence_plate, warranty_note, garage_note, maintenace_note)
select
sn.id,
sn.license_plate,
(select nt.id from notes as nt where nt.type = 1 and nt.note = ExtractValue(sn.sales_note, "/warranty")) as warranty_note,
(select nt.id from notes as nt where nt.type = 1 and nt.note = ExtractValue(sn.sales_note, "/garage")) as garage_note,
(select nt.id from notes as nt where nt.type = 1 and nt.note = ExtractValue(sn.sales_note, "/maintenance")) as maintenance_note
from note_types as nt
但是,如果在note_types
表中找不到銷售的確切注釋,它將失敗。 您可以調整注釋文本比較,用類似的運算符,正則表達式檢查或其他功能代替; 您可以用全字詞代替縮寫,也可以發明自己的MySQL函數。 此外,您可以發明自己的MySQL函數,該函數包含內部select
,如果在note_types
表中未找到note,則返回null
。
如果要更新現有表,則需要執行join
到我提供的相同select
update
查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.