获取SQL UNION中的字段总和

时间:2012-04-07 06:09:33

标签: mysql sql

我如何在这里得到相互字段的SUM?

SELECT first_user_id, mutual
    FROM userprofile_usercontact
UNION ALL
SELECT second_user_id, mutual
    FROM userprofile_usercontact
GROUP BY first_user_id

换句话说,我希望获得SUM(mutual)(first_user_id + second_user_id),其中mutual = 1。

3 个答案:

答案 0 :(得分:2)

SELECT u.user_id, SUM(u.mutual)
  FROM (SELECT first_user_id AS user_id, mutual
          FROM userprofile_usercontact
        UNION ALL
        SELECT second_user_id AS user_id, mutual
          FROM userprofile_usercontact
       ) AS u
 GROUP BY user_id;

评论中的问题是:

  

我如何摆脱互= 0的条目?

像往常一样使用过滤条件:

SELECT u.user_id, SUM(u.mutual)
  FROM (SELECT first_user_id AS user_id, mutual
          FROM userprofile_usercontact
        UNION ALL
        SELECT second_user_id AS user_id, mutual
          FROM userprofile_usercontact
       ) AS u
 WHERE u.mutual != 0   -- or u.mutual <> 0
 GROUP BY user_id;

优化器可能会将条件下推到UNION查询中,因此它将像执行查询一样执行:

SELECT u.user_id, SUM(u.mutual)
  FROM (SELECT first_user_id AS user_id, mutual
          FROM userprofile_usercontact
         WHERE mutual != 0
        UNION ALL
        SELECT second_user_id AS user_id, mutual
          FROM userprofile_usercontact
         WHERE mutual != 0
       ) AS u
 GROUP BY user_id;

最终结果是相同的。

答案 1 :(得分:1)

SELECT SUM(mutual) sm, user_id FROM
(SELECT first_user_id user_id, mutual
    FROM userprofile_usercontact
    UNION ALL
    SELECT second_user_id, mutual
        FROM userprofile_usercontact
        GROUP BY first_user_id) s 

    GROUP BY user_id ORDER BY sm DESC

答案 2 :(得分:0)

Select sum(field) from (
  Select ....
  Union all 
  Select ....
 ) atable
where ....