SQL获取查询中所有用户活动的总和

时间:2019-03-26 11:50:00

标签: php mysql sql

我想从用户表中获取所有用户,并在列中汇总所有用户从文章表中撰写的所有文章的长度

基本上 如果我选择为每个循环运行一个SQL查询,这是一个代码(不好)

SELECT * FROM users
--loop
SELECT SUM(wordcount) AS totalwordcount FROM articles WHERE writer_id = user_id

我使用了LEFT JOIN,但是我只能获得在商品表中显示了user_id的用户列表

SELECT users.name, SUM(article.wordcount) AS xox FROM users LEFT JOIN article ON users.id_usera = article.writer_id WHERE article.editor_status = 'finished' ORDER BY users.id_usera 

通过该查询,我只会使用户的文章表中存在其user_id的用户,但我希望列出所有用户,并且如果该用户不存在其ID的文章,则返回NULL /空。

2 个答案:

答案 0 :(得分:1)

您需要GROUP BY

SELECT u.name, SUM(a.wordcount) AS xox
FROM users u LEFT JOIN
     article a
     ON u.id_usera = a.writer_id AND
        a.editor_status = 'finished' 
GROUP BY u.name;

答案 1 :(得分:0)

SELECT users.name, SUM(article.wordcount) AS TotalWordCount 
FROM users 
LEFT JOIN article ON users.id_usera = article.writer_id 
WHERE article.editor_status = 'finished' 
GROUP BY article.writer_id
ORDER BY users.id_usera