134

我正在执行插入查询,如果已经存在唯一键,则需要将许多列中的大多数更新为新值。它是这样的:

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子句中引用当前行?

4

4 回答 4

203

MySQL 将假定 equals 之前的部分引用 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, ...
于 2010-03-18T18:15:00.147 回答
60

虽然我对此很晚,但在看到那些想要使用INSERT-SELECT带子句查询的人的一些合理问题后GROUP BY,我想出了解决这个问题的方法。

进一步了解Marcus Adams的答案并记GROUP BY入其中,这就是我将如何使用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, ...
于 2015-04-16T08:08:41.520 回答
0

当 SELECT 语句有 GROUP BY 子句时。

    ....
    ON DUPLICATE KEY UPDATE    
    larct=VALUES(larct), lardur=VALUES(lardur),lardist= 
    VALUES(lardist)
于 2021-06-02T10:50:13.970 回答
0

ON DUPLICATE KEY UPDATE a=VALUES(a), b=VALUES(b)当字段名称不同时将不起作用,例如ON DUPLICATE KEY UPDATE a=VALUES(c), b=VALUES(c)有时会失败,但ON DUPLICATE KEY UPDATE a=t.c, b=t.c...可以。

于 2021-12-15T06:52:20.470 回答