两个不同查询的总和

时间:2015-12-29 09:22:37

标签: mysql sum left-join

我必须从2个不同的表格中求和并使用 MySQL 显示它:

表1中的总评论,表2中的总评论:到目前为止我尝试过的是,

SELECT u.name as name, u.username as username, 
( SELECT SUM(total) FROM (SELECT (COUNT(nc.id)) as total FROM table1 as nc WHERE nc.user_id = u.id) UNION ALL (SELECT COUNT(pc.id) AS total FROM table2 pc WHERE pc.user_id = u.id) as finalTotal ) as total_comments
FROM user as u 
GROUP BY u.id

它给了我错误

  

每个派生表都必须有自己的别名

3 个答案:

答案 0 :(得分:1)

如果我理解你需要什么,你必须修改这样的查询:

select u.name,u.username,total as total_comments
from user as u
left join (
    select id,sum(total) as total 
    from(
        select nc.id,count(1) as total
        from table1 as nc
        group by nc.id
        union all
        select pc.id,count(1) as total
        from table2 as pc
        group by pc.id
    ) as t group by id
) comments on comments.id = u.id

答案 1 :(得分:0)

在UNION ALL之前加上你给予所有人的别名..

SELECT u.name as name, u.username as username, 
( SELECT SUM(total) FROM (SELECT (COUNT(nc.id)) as total FROM table1 as nc WHERE nc.user_id = u.id) as vr UNION ALL (SELECT COUNT(pc.id) AS total FROM table2 pc WHERE pc.user_id = u.id) as finalTotal ) as total_comments
FROM user as u 
GROUP BY u.id

答案 2 :(得分:0)

SELECT u.name as name, u.username as username, 
( SELECT SUM(total) FROM 
  (SELECT (COUNT(nc.id)) as total FROM table1 as nc WHERE nc.user_id = u.id

  UNION ALL SELECT COUNT(pc.id) AS total FROM table2 pc WHERE pc.user_id = u.id) as finalTotal ) as total_comments
FROM user as u 
GROUP BY u.id

删除UNION ALL之前和之后的括号并检查。