INSERT INTO …从重复键更新select…

我正在做一个插入查询,如果一个唯一的密钥已经存在,其中大多数列需要更新到新的值。 它是这样的:

INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct, inact, inadur, inadist, smlct, smldur, smldist, larct, lardur, lardist, emptyct, emptydur) SELECT id, uid, t.location, t.animal, t.starttime, t.endtime, t.entct, t.inact, t.inadur, t.inadist, t.smlct, t.smldur, t.smldist, t.larct, t.lardur, t.lardist, t.emptyct, t.emptydur FROM tmp t WHERE uid=x ON DUPLICATE KEY UPDATE ...; //update all fields to values from SELECT, // except for exp_id, created_by, location, animal, // starttime, endtime 

我不确定UPDATE子句的语法应该是什么。 我如何从SELECT子句引用当前行?

MySQL将在等于引用INSERT INTO子句中指定的列之前承担该部分,第二部分引用SELECT列。

 INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct, inact, inadur, inadist, smlct, smldur, smldist, larct, lardur, lardist, emptyct, emptydur) SELECT id, uid, t.location, t.animal, t.starttime, t.endtime, t.entct, t.inact, t.inadur, t.inadist, t.smlct, t.smldur, t.smldist, t.larct, t.lardur, t.lardist, t.emptyct, t.emptydur FROM tmp t WHERE uid=x ON DUPLICATE KEY UPDATE entct=t.entct, inact=t.inact, ... 

尽pipe我对此很迟,但是在看到一些想要使用带有GROUP BY子句的INSERT-SELECT查询的合法问题之后,我想出了这个方法。

进一步考虑马库斯·亚当斯和会计GROUP BY的答案,这是我将如何通过Subqueries in the FROM Clause使用Subqueries in the FROM Clause来解决问题

 INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct, inact, inadur, inadist, smlct, smldur, smldist, larct, lardur, lardist, emptyct, emptydur) SELECT sb.id, uid, sb.location, sb.animal, sb.starttime, sb.endtime, sb.entct, sb.inact, sb.inadur, sb.inadist, sb.smlct, sb.smldur, sb.smldist, sb.larct, sb.lardur, sb.lardist, sb.emptyct, sb.emptydur FROM (SELECT id, uid, location, animal, starttime, endtime, entct, inact, inadur, inadist, smlct, smldur, smldist, larct, lardur, lardist, emptyct, emptydur FROM tmp WHERE uid=x GROUP BY location) as sb ON DUPLICATE KEY UPDATE entct=sb.entct, inact=sb.inact, ...