2010-03-18 125 views
95

我正在做一個插入查詢,其中大多數列需要更新爲新的值,如果一個唯一的鍵已經存在。它是這樣的:INSERT INTO ...從重複鍵更新

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條款中的當前行?

回答

125

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, ... 
+5

@dnagirl:**提示**不要試圖更新任何PK列,只有需要更新的列纔會進入列表 – lexu 2010-03-18 18:18:39

+37

您的建議語法有效,並且需要't.'。我還發現了一篇關於xaprb的文章(http://www.xaprb.com/blog/2006/02/21/flexible-insert-and-update-in-mysql/),它使用這種語法:'在重複密鑰更新b上=值(b),c =值(c)'。這也適用。 – dnagirl 2010-03-18 18:43:47

+7

注意:當SELECT語句具有GROUP BY子句時,這不起作用 – joHN 2014-07-30 11:44:40

28

雖然我很晚這一點,但看到對於那些誰想要使用INSERT-SELECT查詢與GROUP BY從句中某些合理的問題後,我想出瞭解決有關此。

馬庫斯·亞當斯的進一步回答和會計它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, ... 
+6

對於COUNT,GROUP等查詢,這是正確答案。謝謝。 – Kostanos 2015-06-26 16:28:40

+0

非常感謝,夥計!我非常喜歡這種方法,特別是因爲它允許我創建一個像Continuous Query這樣的機制,這是InfluxDB的功能。 – Miere 2016-06-15 17:12:45

+0

很高興聽到這個消息 – iConfused 2016-06-15 23:39:23