简体   繁体   English

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

[英]SQL get all users activity summed in a query

I want get all users from users table and have a column summed up on all articles length written by all users from article table 我想从用户表中获取所有用户,并在文章表中汇总所有用户写的所有文章长度的列

Basically Here is a code if I choose to run an SQL query for each loop (not good) 基本上这是一个代码,如果我选择为每个循环运行一个SQL查询(不好)

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

I have used LEFT JOIN but I can only get a list of users with their user_id present on article table 我已经使用了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 

With this query, I only get users with their user_id present in the article table but I want all users listed and NULL/empty returned if the user has no article with his/her id present 通过此查询,我只获得在文章表中存在其user_id的用户,但我希望列出所有用户,如果该用户没有在其ID中存在的文章,则返回NULL /空

You need GROUP BY : 您需要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;
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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM