有没有办法在mysql中的重复密钥更新插入中进行增量更新?
示例w /错误:
insert into blah (user_id, prefix, email_id, field, source)
select user_id, substring(name, 1, 3), contact_email_id, 2, source from address_book
on duplicate key update source = source + values(source);
ERROR 1052 (23000): Column 'source' in field list is ambiguous
答案 0 :(得分:1)
如果您将表前缀添加到列名称,即blah.source,address_book.source?
,该怎么办?答案 1 :(得分:1)
否,您无法指定source = source + values(source);
因为源表blah
未包含在select
中,使用别名无法解决。
解决方法将使用left join
insert into blah (user_id, prefix, email_id, field, source)
select
ab1.user_id, substring(ab1.name, 1, 3), ab1.contact_email_id, 2,
if(ab2.source, ab1.source+ab2.source, ab1.source)
from
address_book ab1
left join
blah1 as ab2
on
ab1.user_id=ab2.user_id
on duplicate key
update source = values(source);
/* values(source) = ab1.source+ab2.source if duplicate found */
谨防1:N
关系