简体   繁体   English

当满足条件时,mysql从另一个表中替换表数据

[英]mysql replace table data from another table when condition is met

I am working on the database for a Wordpress Multisite install and need to copy multiple fields (but not all) from one table into another table, replace existing content and/or add row if they don't exist. 我正在为Wordpress Multisite安装数据库,需要将多个字段(但不是全部)从一个表复制到另一个表,替换现有内容和/或添加行(如果不存在)。

There are similar answers elsewhere but I can't seem to figure this out. 在其他地方也有类似的答案,但我似乎无法弄清楚。

tables are sourcetable and targettable 表是源表和目标表

columns are option_name and option_value 列是option_name和option_value

basically, if option_name field = condition1 is present in targettable copy option_value field from sourcetable and replace targettable option_value field, if not present then add it 基本上,如果option_name field = condition1存在于targettable中,则从sourcetable复制option_value字段并替换targettable option_value字段,如果不存在,则添加它

would like to update/replace multiple fields with one query 想用一个查询更新/替换多个字段

REPLACE or UPDATE option_value_field in targettable with data 
from sourcetable value_field 
where name_field equals "condition1"

REPLACE or UPDATE option_value_field in targettable with data 
from sourcetable value_field 
where name_field equals "condition2"

REPLACE or UPDATE option_value_field in targettable with data 
from sourcetable value_field
where name_field equals "condition3" (add if does not exist)

thanks 谢谢

Make option_name field unique, and use INSERT...ON DUPLICATE KEY UPDATE statement to insert/replace values in targettable - 使option_name字段唯一,并使用INSERT ... ON DUPLICATE KEY UPDATE语句在targettable插入/替换值-

INSERT INTO targettable
SELECT * FROM sourcetable
ON DUPLICATE KEY UPDATE option_value = VALUES(option_value)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM