MySQL 查询:更新 and/or 追加
MySQL Query: UPDATE and/or APPEND
我有一个临时 table 用于插入主数据库。
临时 table 名为“temp_table”
大师table是“大师”
我目前使用以下命令更新“master”
SELECT COUNT(*) FROM master;
SHOW COLUMNS FROM master;
INSERT INTO master
SELECT * FROM temp_table
ON DUPLICATE KEY UPDATE email = VALUES(email), phone = VALUES(phone)
现在,我希望能够将“temp table”中的字段(计数器)附加到“master”中。该字段已存在于两个 table 中,我只想能够更新或追加它。
master 中的“计数器”字段可能为空,或者它可能已经包含一个数值。
In cases where the value exists, it should append separated by a comma. Format (88,89,90)
In cases where the it's empty, it should update (88)
提前致谢。
我想你想要:
on duplicate key update
email = values(email),
phone = values(phone),
counter = case when counter is null
then values(counter)
else concat(counter, ',', values(counter))
end
你也可以用 coalesce()
来表达这个意思,尽管这个表达方式可能有点难以理解:
on duplicate key update
email = values(email),
phone = values(phone),
counter = concat(
coalesce(concat(counter, ','), ''),
values(counter)
)
我有一个临时 table 用于插入主数据库。
临时 table 名为“temp_table” 大师table是“大师”
我目前使用以下命令更新“master”
SELECT COUNT(*) FROM master;
SHOW COLUMNS FROM master;
INSERT INTO master
SELECT * FROM temp_table
ON DUPLICATE KEY UPDATE email = VALUES(email), phone = VALUES(phone)
现在,我希望能够将“temp table”中的字段(计数器)附加到“master”中。该字段已存在于两个 table 中,我只想能够更新或追加它。
master 中的“计数器”字段可能为空,或者它可能已经包含一个数值。
In cases where the value exists, it should append separated by a comma. Format (88,89,90)
In cases where the it's empty, it should update (88)
提前致谢。
我想你想要:
on duplicate key update
email = values(email),
phone = values(phone),
counter = case when counter is null
then values(counter)
else concat(counter, ',', values(counter))
end
你也可以用 coalesce()
来表达这个意思,尽管这个表达方式可能有点难以理解:
on duplicate key update
email = values(email),
phone = values(phone),
counter = concat(
coalesce(concat(counter, ','), ''),
values(counter)
)