选择两个选择sql / oracle

时间:2014-01-04 12:42:44

标签: mysql sql

我想在单个查询中加入join 2 select:

以下是两个查询。

        SELECT player_id, SUM(score) score
     FROM (
      SELECT id_p1 player_id, score_p1 score
        FROM matchs
      UNION ALL
      SELECT id_p2, score_p2
        FROM matchs
      ) q
      GROUP BY player_id 

AND

SELECT player_id, SUM(score) score
    FROM (
      SELECT id_p1 player_id, score_p2 score
        FROM matchs
      UNION ALL
      SELECT id_p2, score_p1
        FROM matchs
    ) q
     GROUP BY player_id

谢谢!

2 个答案:

答案 0 :(得分:1)

试试这个

SELECT table1.player_id, table1.score score1, table2.score score2,
       abs(table1.score - table2.score) difference
FROM (
       SELECT player_id, SUM(score) score
       FROM (
              SELECT player1_id player_id, score_p1 score FROM matchs
              UNION ALL
              SELECT player2_id , score_p2 FROM matchs
             ) q GROUP BY player_id
      ) table1
INNER JOIN 
          (
            SELECT player_id, SUM(score) score
            FROM (
                   SELECT player1_id player_id, score_p2 score FROM matchs
                   UNION ALL
                   SELECT player2_id , score_p1 FROM matchs
                  ) q GROUP BY player_id
          ) table2 ON table1.player_id = table2.player_id

<强> SQL Fiddle Demo

答案 1 :(得分:0)

理想情况下,可以使用FULL JOIN

执行此操作
SELECT      COALESCE(t1.player1_id, t2.player2_id)
            SUM(COALESCE(t1.score_p1,0) + COALESCE(t2.score_p2,0))
FROM        table_name t1
  FULL JOIN table_name t2 ON t1.player1_id = t2.player2_id
GROUP BY    COALESCE(t1.player1_id, t2.player2_id)

然而,遗憾的是MySQL没有对这种连接操作的原生支持。相反,可以通过在UNIONLEFT JOIN之间设置RIGHT JOIN来模拟它,然后汇总:

SELECT p, SUM(s) FROM (

  SELECT       t1.player1_id p, SUM(t1.score_p1 + IFNULL(t2.score_p2,0)) s
  FROM         table_name t1
    LEFT JOIN  table_name t2 ON t1.player1_id = t2.player2_id
  GROUP BY     t1.player1_id

  UNION

  SELECT       t2.player2_id, SUM(IFNULL(t1.score_p1,0) + t2.score_p2)
  FROM         table_name t1
    RIGHT JOIN table_name t2 ON t1.player1_id = t2.player2_id
  GROUP BY     t2.player2_id

) t GROUP BY p

sqlfiddle上查看。