UPDATE where in () 相同ID的话只操作一次 怎么办?
UPDATE table1 SET a = a + 10
WHERE id IN
(SELECT TOP 10 id FROM table2 ORDER BY hit)
表1是用户表
表2其实 记录表1用户发布的日记 (ID贯穿)
现上面查询语句 要给日记hit字段前10名用户 a+10
但是子查询中可能有重复记录 有的话数据库就操作了一次
怎么才能重复操作?
问题简单化就是
UPDATE table1 SET a = a + 10
WHERE id IN (5,5,5)
这条语句实际上只对ID等于5的记录实行一次 a = a + 10
如何才能实现 操作3次 a = a + 10 ?
困扰中。
------解决方案-----------------------try
UPDATE table1 SET a = a + 10
from (SELECT TOP 10 id FROM table2 ORDER BY hit) b
WHERE id = b.id
------解决方案--------------------用循环
declare @i int,@j int
set @j=2
while @j <10
begin
UPDATE table1 SET a = a + 10
WHERE id in (select [id] from table2 where id in (select top 10 [id] from table1) having count([id])=2)
@j++
end
大概思路是先全更新一次,然后找出出现2次得在更新以次,直到。。。呵呵
可能写得不对!但是思路应该没问题巴
------解决方案--------------------UPDATE t1
SET a = a + 10 * t2.cnt
FROM table1 t1,
(SELECT id,COUNT(*) AS cnt
FROM
(SELECT TOP 10 id FROM table2 ORDER BY hit) x
GROUP BY id) t2
WHERE t1.a=t2.id