我有一个表,其中主键是两列的组合。我想根据我的主键更新多行
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声明,但不知道当键是两个键的组合时如何使用它。这是我使用 CASE 编写的查询.它改变了我所有的行。如果当前记录不符合记录 3 之类的任何 when 条件,则其更改为默认值 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
最佳答案
This is the query I wrote using CASE but I got errors in query
把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')
关于mysql - 多次更新查询mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7791583/