Mysql中的嵌套查询更新?

时间:2012-01-30 02:02:30

标签: mysql sql

我有以下查询:

SELECT `peers`.uid, `user`.userid FROM `peers`, `user` WHERE `user`.userid = `peers`.uid
FF。是查询的结果

userid,uid
1,1
1,1
1,1
3,3
96,96
96,96

要更新结果,我有ff查询设置:

UPDATE `user`
   INNER JOIN (    
   SELECT `peers`.uid, `user`.userid FROM `peers`, `user` WHERE `user`.userid = `peers`.uid
       ) AS my_current_select ON `user`.userid = my_current_select.userid
   SET `user`.credits = `user`.credits + 0.25

但是,更新查询只更新了3次,每次加上一次0.25个信用到用户ID 1,3,96

这不是我想要的。我想在查询的每一行结果中唯一地添加0.25个学分 例如:

UID 1: UID1.credit = UID1.credit + 0.25 * 3 
UID 3: UID3.credit = UID3.credit + 0.25 * 1 
UID 3: UID96.credit = UID96.credit + 0.25 * 2

如何实现这一结果?

3 个答案:

答案 0 :(得分:4)

也许将您的内部查询更改为:

SELECT `user`.userid, COUNT(`peers`.uid) as count 
FROM `peers`, `user` 
WHERE `user`.userid = `peers`.uid 
GROUP BY `user`.userid

得到:

userid,count
1,3
3,1
96,2

然后在您的主查询中执行:

UPDATE `user`
   INNER JOIN (    
   SELECT `user`.userid, COUNT(`peers`.uid) as count 
    FROM `peers`, `user` 
    WHERE `user`.userid = `peers`.uid 
    GROUP BY `user`.userid
       ) AS my_current_select ON `user`.userid = my_current_select.userid
   SET `user`.credits = `user`.credits + 0.25*my_current_select.count

答案 1 :(得分:0)

UPDATE `user`
SET credits=credits+0.25
WHERE userid IN (
    SELECT `user`.userid
    FROM `peers`, `user`
    WHERE `user`.userid = `peers`.uid
)

这被称为嵌套查询,正如您所推测的那样。事实上,您需要加入的唯一原因是因为您只选择中的条目 userpeers表(它是隐式内连接)

如果您只想更新所有用户,无论他们是否在peers,您都可以:

UPDATE `user` SET credits=credits+0.25

答案 2 :(得分:0)

update u
set u.credit = u.credit + (0.25 * c.credits)
from user u
join (select us.userid, count(p.uid) as credits
      from user us join peers p on us.userid = p.uid
      group by us.userid) c
     on u.userid = c.userid

实际上,除非您的表名包含特殊字符或保留字,否则反引号是非常不必要的。我也更喜欢把SET子句放在第一位,我认为这有助于提高可读性(在定义数据源之前先说明你打算做什么。)另外,我强烈建议使用真正的连接语法(ON)而不是使用where子句如果你使用别名,你的生活会更简单。