2010-07-26 54 views
11

我想要做的是:MySQL查詢更新場到最大(場)+ 1

UPDATE table SET field = MAX(field) + 1 WHERE id IN (1, 3, 5, 6, 8); 

這句話的語義,在我的腦海裏,會是第一個數據庫將熄滅,並確定我field的最大值是table。然後,它會加1到該值,並將結果值分配給 1,3,5,6和8行的field列。似乎很簡單...似乎很簡單...

當我嘗試運行查詢雖然,MySQL的扼流圈,並說:

ERROR 1111 (HY000): Invalid use of group function 

你有什麼祕密醬,以獲得我想要的結果?

問候, 維克

回答

18

嘗試

UPDATE TABLE set field = ((SELECT selected_value FROM (SELECT MAX(field) AS selected_value FROM table) AS sub_selected_value) + 1) WHERE id in (1,3,5,6,8) 

大搖大擺從Here扯掉

+0

謝謝你做到了! – vicatcu 2010-07-26 04:52:00

+1

+1:即使我兩分鐘擊敗了你 – 2010-07-26 04:54:58

+1

你確實打敗了我,但你錯過了一個右括號:P – GWW 2010-07-26 04:58:22

5

爲了獲得mysql-error-1093周圍,使用子查詢/派生表/內嵌視圖:

UPDATE table 
     SET field = (SELECT x.max_field 
          FROM (SELECT MAX(t.field) + 1 AS max_field 
             FROM TABLE t 
             WHERE t.id IN (1,3,5,6,8)) x) 
+0

't.id後缺少一個括號IN(1,3,5,6,8)**)** x)' – Ultrazz008 2016-10-29 20:05:25