多个更新查询mysql

时间:2011-10-17 09:09:25

标签: mysql

我有一个表,其中主键是两列的组合。我想根据我的主键更新多行

StationId   ServerDate          Status
1           2011-05-05 01:00:00 0
1           2011-05-06 01:00:00 1
2           2011-05-05 01:00:00 2

我的更新查询目前看起来像

Update data set status = 1 where StationId = '1' and  ServerDate = '2011-05-05 01:00:00'
Update data set status = 2 where StationId = '1' and  ServerDate = '2011-05-06 01:00:00'

我正在考虑使用CASE语句,但是当key是两个键的组合时,无法确定如何使用它。这是我使用CASE编写的查询。它改变了我的所有行。如果当前记录不属于记录3之类的任何条件,则其更改为默认值0.我希望该记录保留以前的值。

UPDATE data set status = CASE 
   WHEN StationId = '1' and  ServerDate = '2011-05-05 01:00:00' THEN 1 
   WHEN StationId = '1' and  ServerDate = '2011-05-06 01:00:00' THEN 2 
END 

4 个答案:

答案 0 :(得分:3)

  

这是我使用CASE编写的查询,但我在查询中遇到错误

删除END关键字后的“CASE”,它应该没问题:

UPDATE data 
   SET status = 
     CASE 
       WHEN stationId = '1' and ServerDate = '2011-05-05 01:00:00' THEN 1 
       WHEN stationId = '1' and ServerDate = '2011-05-06 01:00:00' THEN 2 
       WHEN stationId = '2' and ServerDate = '2011-05-05 01:00:00' THEN 3
     END
WHERE stationId IN ('1', '2')
  AND ServerDate in ('2011-05-05 01:00:00', '2011-05-06 01:00:00')

答案 1 :(得分:2)

您的查询应该是:(已编辑)

UPDATE data set status = 
(
   CASE 
       WHEN StationId = '1' AND ServerDate = '2011-05-05 01:00:00' THEN 1 
       WHEN StationId = '2' AND ServerDate = '2011-05-06 01:00:00' THEN 2 
    END 
)
WHERE StationId IN ('1','2')

答案 2 :(得分:2)

您只需删除最后一个“CASE”

UPDATE data set status = CASE 
   WHEN StationId = '1' and  ServerDate = '2011-05-05 01:00:00' THEN 1 
   WHEN StationId = '1' and  ServerDate = '2011-05-06 01:00:00' THEN 2 
END 

答案 3 :(得分:0)

当你处理多行时,你可以使StationId成为更快查询的索引。

mysql>CREATE INDEX index_name ON tableName(StationId);