我有一个表,用于在posts
表中存储用户提交的帖子。用户还可以“喜欢这些帖子。相似内容存储在likes
表格中,每行一行,列id
,user
和postid
。
我现在已在likes
表格中添加了一列posts
。如何更新每个帖子的likes
表格中的posts
列,以反映likes
表中该帖子的相似数量?
TIA!
答案 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);