从另一个表更新表

时间:2013-05-20 07:04:17

标签: mysql

我有一个表,用于在posts表中存储用户提交的帖子。用户还可以“喜欢这些帖子。相似内容存储在likes表格中,每行一行,列iduserpostid

我现在已在likes表格中添加了一列posts。如何更新每个帖子的likes表格中的posts列,以反映likes表中该帖子的相似数量?

TIA!

3 个答案:

答案 0 :(得分:1)

UPDATE posts p
JOIN (SELECT postid, COUNT(*) c
      FROM likes
      GROUP BY postid) l
ON p.id = l.postid
SET p.likes = l.c

答案 1 :(得分:1)

带有子查询的版本

UPDATE posts p
   SET likes = (SELECT COUNT(*) FROM likes WHERE postid = p.postid)

<强> SQLFiddle

答案 2 :(得分:0)

update posts p
left join
(
select postid, count(*) likes
from likes
group by postid
) l on p.id = l.postid
set p.likes = ifnull(l.likes, 0);