考虑以下表格
users tweets
-------------------- -----------------------------
user_id neu pos neg id _date user_id class
-------------------- -----------------------------
1 1 2011-02-13 1 1
2 2 2011-02-13 1 2
3 2011-02-15 2 1
4 2011-02-16 2 3
5 2011-02-16 2 3
数据库中的每条推文都经过分析和分类。 tweets.class
可以是1
(中立),2
(正面)或3
(负面)。我需要一个查询来计算每个用户的所有neu
(中性,pos
(正)和neg
(否定)推文。查询的最终结果将是和UPDATE
d users
- 像这样的表:
users
--------------------
user_id neu pos neg
--------------------
1 1 1 0
2 1 0 3
我现在有,但这根本不起作用。我正朝着正确的方向前进吗?
update users u left join (
select count(t.id) as neu from tweets t where class = 1
) on u.user_id = t.user_id
set u.neu = coalesce(neu,0)
答案 0 :(得分:1)
这应该有效:
UPDATE users a
INNER JOIN (SELECT user_id,
SUM(IF(class = 1, 1, 0)) AS class_1,
SUM(IF(class = 2, 1, 0)) AS class_2,
SUM(IF(class = 3, 1, 0)) AS class_3
FROM tweets
GROUP BY user_id
) b
ON a.user_id = b.user_id
SET a.neu = b.class_1,
a.pos = b.class_2,
a.neg = b.class_3;