[英]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.