这是我的表:
id delivery_mode old_delivery_mode
123 email sms
126 sms sms
139 email facebook
147 facebook email
198 sms sms
210 sms email
我想用这些值更新我的表字段值:
sms=100
email=200
facebook=300
那样:
id delivery_mode old_delivery_mode
123 200 100
126 100 100
139 200 300
147 300 200
198 100 100
210 100 200
我想在单个SQL查询中执行此操作。
我该怎么做?
答案 0 :(得分:2)
UPDATE YOUR_TABLE_NAME
SET delivery_mode =
CASE
WHEN delivery_mode = 'sms' THEN '100'
WHEN delivery_mode = 'email' THEN '200'
WHEN delivery_mode = 'facebook' THEN '300'
WHEN delivery_mode THEN delivery_mode
END,
old_delivery_mode =
CASE
WHEN old_delivery_mode = 'sms' THEN '100'
WHEN old_delivery_mode = 'email' THEN '200'
WHEN old_delivery_mode = 'facebook' THEN '300'
WHEN old_delivery_mode THEN old_delivery_mode
END
答案 1 :(得分:0)
是的,这是可能的 - 您可以使用INSERT ... ON DUPLICATE KEY UPDATE。
使用示例:
INSERT INTO table (id,Col1,Col2) VALUES (1,1,1),(2,2,3),(3,9,3),(4,10,12)
ON DUPLICATE KEY UPDATE Col1=VALUES(Col1),Col2=VALUES(Col2);
我发现它here
这就是你要找的东西吗?
答案 2 :(得分:0)
我不确定这是否是你想要的
Update table1 set
delivery_mode = case delivery_mode when 'sms' then '100' when 'email' then '200' when facebook then '300' end,
old_delivery_mode = case delivery_mode when 'sms' then '100' when 'email' then '200' when facebook then '300' end
答案 3 :(得分:0)
这是你想要的吗?
update your_table
set old_delivery_mode = delivery_mode,
delivery_mode =
case delivery_mode
when 'sms' then '100'
when 'email' then '200'
when 'facebook' then '300'
end
where delivery_mode in ('sms','email','facebook')
在sqlite下测试。
答案 4 :(得分:0)
SQL等价物将使用CASE,如下所示:
UPDATE myTable
SET delivery_mode = CASE delivery_mode
WHEN 'sms' THEN '100'
WHEN 'email' THEN '200'
WHEN 'facebook' THEN '300'
ELSE delivery_mode END -- ELSE to make sure other values aren't touched
, old_delivery_mode = CASE old_delivery_mode
WHEN 'sms' THEN '100'
WHEN 'email' THEN '200'
WHEN 'facebook' THEN '300'
ELSE old_delivery_mode END
-- And WHERE to make sure only the applicable rows are updated
WHERE delivery_mode IN ('sms','email','facebook')
OR old_delivery_mode IN ('sms','email','facebook')
其中有一些额外的检查(已评论),因为我们不知道这些列可能具有的其他值,或者此更新应考虑整个表中的行数。