group by + given AND在同一输出中获得投票

时间:2011-06-02 22:47:47

标签: mysql group-by

我有投票表,其中数据以这种格式写成:

id_user|id_user2|value
1|2|-1
1|3|1
5|3|1
2|1|-1

id_user是投票的用户,id_user2是获得投票的用户,如果他获得正面或负面投票,则值代表。好吧,我的问题是,我想展示每个用户如何在同一输出中给予和获得投票。以下是我想从上面输入的输出看起来:

id_user|given|gotten
1|0|-1
2|-1|-1
3|0|2
5|1|0

我不知道该怎么做,我只知道如何通过两个单独的查询显示这个。在这种情况下,它将是:

SELECT id_user2,SUM(value) FROM `table` GROUP BY id_user2

SELECT id_user,SUM(value) FROM `table` GROUP BY id_user

1 个答案:

答案 0 :(得分:1)

只需加入查询:

SELECT
  gotten.id_user,
  gotten.gotten,
  given.given
FROM
(
  SELECT
    id_user2   AS id_user,
    SUM(value) AS gotten
  FROM
    table
  GROUP BY
    id_user2
) gotten
JOIN -- Join the current row with rows verifying...
(
  SELECT
    id_user,
    SUM(value) AS given
  FROM
    table
  GROUP BY
    id_user
) given ON given.id_user =  gotten.id_user -- ... this is the same user.

N.B。如果用户没有给予或没有得到投票,它将不会为他返回任何东西。如果您需要这些案例的结果,即使在左表或右表中没有符合条件的行,也要使用完整的外部联接来加入。

SELECT
  gotten.id_user,
  gotten.gotten,
  given.given
FROM
(
  SELECT
    id_user2   AS id_user,
    SUM(value) AS gotten
  FROM
    table
  GROUP BY
    id_user2
) gotten
FULL OUTER JOIN -- Join the current row with rows verifying...
(
  SELECT
    id_user,
    SUM(value) AS given
  FROM
    table
  GROUP BY
    id_user
) given ON given.id_user =  gotten.id_user -- ... this is the same user.

如果没有给予或获得投票,您将获得空值。