你好我有这样的表:
表格条目:
id | TOTAL_COMMENTS
_____________________
1 | 0
2 | 0
3 | 0
4 | 0
表评论:
id |开斋节评论
_____________________
1 | 1 |评论sdfd
2 | 1 |测试测试
3 | 1 |评论文本
4 | 2 |虚假评论
5 | 2 |样本评论
6 | 1 | fg fgh dfh
我写的查询:
UPDATE entry
SET total_comments = total_comments + 1
WHERE id IN ( SELECT eid
FROM comments
WHERE id IN (1,2,3,4,5,6))
我得到的结果是:
表格条目:
id | TOTAL_COMMENTS
_____________________
1 | 1
2 | 1
3 | 0
4 | 0
预期结果:
表格条目:
id | TOTAL_COMMENTS
_____________________
1 | 4
2 | 2
3 | 0
4 | 0
任何帮助将不胜感激。
答案 0 :(得分:16)
使用:
UPDATE entry
SET total_comments = (SELECT COUNT(*)
FROM COMMENTS c
WHERE c.eid = id
GROUP BY c.eid)
WHERE id IN ( SELECT eid
FROM comments
WHERE id IN (1,2,3,4,5,6))
答案 1 :(得分:3)
如果你真的需要在一个单独的表中使用total_comments,我会把它作为一个VIEW。
CREATE VIEW entry AS
SELECT id, COUNT(comments) AS total_comment
FROM comments
GROUP BY id
这样就可以避免完全更新total_comments表的维护任务。
答案 2 :(得分:1)
这正是我所期待的。 id是你给它的集合,所以total_comments = total_comments + 1。
它不会为每个具有相同值的实例添加一个:这不是IN的工作方式。 IN将返回一个简单的布尔值yes / no。
答案 3 :(得分:1)
尝试:
UPDATE entry
SET total_comments = (SELECT COUNT(*)
FROM comments
WHERE entry.id = comments.eid
GROUP BY id)
答案 4 :(得分:0)
UPDATE entry e
SET total_comments = ( SELECT COUNT(*) FROM comments WHERE eid = e.id)
WHERE
e.id in (SELECT eid FROM comments WHERE id IN (1,2,3,4,5,6))