是否可以通过一个查询更新和递增几行的值?
我有以下餐桌服务:
id | name | count | created_at | updated_at
我希望每次用户在搜索中选择某些服务时都更新计数(这是通过GUI完成的,用户可以选择一个或多个服务,而我正在获取这些服务的ID)。< / p>
当选择多个服务时,我可以对每个服务执行一个查询,但这似乎不是很有效。
示例:
我需要一次更新7个服务,并为每个服务增加计数值:
UPDATE services SET count = count + 1 WHERE id = 28
UPDATE services SET count = count + 1 WHERE id = 29
UPDATE services SET count = count + 1 WHERE id = 39
UPDATE services SET count = count + 1 WHERE id = 44
UPDATE services SET count = count + 1 WHERE id = 296
UPDATE services SET count = count + 1 WHERE id = 294
UPDATE services SET count = count + 1 WHERE id = 111
是否可以在一个查询中执行此更新?
答案 0 :(得分:3)
我需要一次更新7个服务并增加计数值 他们每个人:
UPDATE services SET count = count + 1 WHERE id = 28
UPDATE services SET count = count + 1 WHERE id = 29
UPDATE services SET count = count + 1 WHERE id = 39
UPDATE services SET count = count + 1 WHERE id = 44
UPDATE services SET count = count + 1 WHERE id = 296
UPDATE services SET count = count + 1 WHERE id = 294
UPDATE services SET count = count + 1 WHERE id = 111
是否可以在一个查询中执行此更新?
可以重写为一个查询。
查询
UPDATE
services
SET
count = count + 1
WHERE
id IN(28, 29, 39, 44, 296, 294, 111)
答案 1 :(得分:0)
您可以尝试这样:
update table set `count` = `count` + 1
以上查询将更新所有行。
如果要更新特定行,可以在以下条件中添加:
update table set `count` = `count` + 1 where name = 'searchText'