[英]MYSQL query check if ID exist and copy column row values to another table related column names
我正在嘗試從一個數據庫表中保存 Mysql 行數據,並通過 PhpMyAdmin 在新數據庫表中復制值,但存在問題。
我缺乏知識是在這里向高級用戶尋求幫助的結果。 復制、加入、合並、刪除或其他:D..我真的不確定解決這個問題的最佳方法是什么。
表 1(舊)有列:id、product_id、標識符、內容
內容- *(LONGTEXT) 內容
表 2(新)有列:
我需要檢查 mysql 查詢與表 1 中的post_id相比,表 2 中的id是否存在。
如果不存在跳到另一條記錄。
如果存在,則從稱為“標識符”的表 1 列檢查記錄名稱/值,例如數量、顏色、折扣、價格 1、價格 2 並將內容列值復制到表 2 列(名稱相關 - 在表 1 列標識符的行中找到.)
為了簡化...檢查表 1 中的 ID。如果 ID 是好的使用標識符值並將 CONTENT 列值從表 1 復制到相關 ID 和表 2 中的列名。
您可以使用條件聚合在子查詢中 pivot 源 EAV 表,然后將其與目標表連接以進行更新。 coalesce()
可用於處理源表中的missig 屬性。
update table2 t2
inner join (
select
post_id,
max(case when identifier = 'quantity' then content end) quantity,
max(case when identifier = 'color' then content end) color,
max(case when identifier = 'discount' then content end) discount,
max(case when identifier = 'price1' then content end) price1,
max(case when identifier = 'price2' then content end) price2
from table1
group by post_id
) t1 on t1.post_id = t2.id
set
t2.quantity = coalesce(t1.quantity, t2.quantity),
t2.color = coalesce(t1.color, t2.color)
t2.discount = coalesce(t1.discount, t2.discount)
t2.price1 = coalesce(t1.price1, t2.price1)
t2.price2 = coalesce(t1.price2, t2.price2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.