1

我将如何在这里获得共同领域的总和?

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。

4

3 回答 3

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;

最终结果当然是一样的。

于 2012-04-07T06:12:28.817 回答
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
于 2012-04-07T06:15:06.800 回答
0
Select sum(field) from (
  Select ....
  Union all 
  Select ....
 ) atable
where ....
于 2012-04-07T06:11:07.803 回答