更新位置字段是最小的数字

时间:2015-02-24 10:29:23

标签: mysql sql-update

我想我是从错误的角度来看待这个问题,但我不能想出一种方法来实现这个目标。我的查询如下:

UPDATE my_table AS T0 
JOIN my_table_2 AS T1
ON T0.timestamp = T1.timestamp  AND T0.id = T1.id

SET lat = lat + 1

WHERE T0.duration = 'd'
AND T0.unique >= 0 
AND T0.unique <= 5 

我需要更新T0.unique等于0到5之间的最小数字的位置。所以基本上如果上面的行返回3行,因为一行中有T0.unique = 2,另一行中有T0.unique = 3,并且T0.unique = 4在另一行,然后我只希望它实际更新它所在的最低数字,即T0.unique = 2

我希望有一些MySQL语法,我不知道会这样做。

2 个答案:

答案 0 :(得分:1)

你能不能这样做:

UPDATE mytable AS T0
SET lat = lat + 1
WHERE T0.duration = 'd' AND T0.unique BETWEEN 0 AND 5
--- possible alternative to join, allows use of ORDER BY and LIMIT in statement
AND EXISTS ( SELECT T1.id FROM mytable2 AS T1 
    WHERE T0.timestamp = T1.timestamp AND T0.id = T1.id )
ORDER BY T0.unique ASC
LIMIT 1

这将最多更新1条记录,而ORDER BY会确保它是unique列中值最低的记录。

答案 1 :(得分:0)

你可以试试这个:

UPDATE my_table t0 
  JOIN my_table_2 t1 
    ON t0.timestamp = t1.timestamp
   AND t0.id = t1.id
   SET t0.lat = t0.lat + 1 
 WHERE t0.duration = 'd'
   AND t0.unique BETWEEN 0 AND 5