使用MySQL加入RIGHT JOIN或UNION

时间:2014-08-03 03:13:42

标签: mysql sql join union

我有一张桌子:

+----+--------+-------+
| ID | Winner | Loser |
+----+--------+-------+
|  1 |      1 |     4 |
|  5 |      1 |     2 |
|  6 |      1 |     3 |
|  3 |      2 |     3 |
|  4 |      2 |     4 |
|  2 |      3 |     4 |
+----+--------+-------+

赢家和输家都是来自另一张桌子的ITEM ID。

我正在尝试实现一个返回列的查询: ITEM ID,CountWinners,CountLosers。

目的是,对于每个itemID,该项目将赢得X场比赛并且输掉一场比赛。如果有胜利的关系,我可以按损失排序

SELECT t1.ID, t1.WinnerCount, t2.ID, t2.LoserCount from
(Select winner as ID, count(winner) as WinnerCount from rp_poss group by winner) as t1
FULL OUTER JOIN
(Select loser as ID, count(loser) as LoserCount from rp_poss group by loser) as t2
ON t1.ID=t2.ID

返回:

+------+-------------+----+------------+
|  ID  | WinnerCount | ID | LoserCount |
+------+-------------+----+------------+
| 2    | 2           |  2 |          1 |
| 3    | 1           |  3 |          2 |
| NULL | NULL        |  4 |          3 |
+------+-------------+----+------------+

而不是

+----+-------------+------------+
| ID | WinnerCount | LoserCount |
+----+-------------+------------+
|  1 |           3 | 0          |
|  2 |           2 | 1          |
|  3 |           1 | 2          |
|  4 |           0 | 3          |
+----+-------------+------------+

我尝试过使用UNION ALL但无法使用它。有什么想法吗?

4 个答案:

答案 0 :(得分:0)

select t_all.id, 
 coalesce(WinnerCount,0) WinnerCount, 
 coalesce(LoserCount,0) LoserCount
from (select distinct winner id from mytable
union select distinct loser id from mytable) t_all
left join (select winner, count(*) WinnerCount
    from mytable group by winner) winners on t_all.id = winners.winner
left join (select loser, count(*) LoserCount
    from mytable group by loser) losers on t_all.id = losers.loser
order by WinnerCount, LoserCount

答案 1 :(得分:0)

我会使用像这样的联合(使用条件聚合):

小提琴: http://sqlfiddle.com/#!2/27ef6/3/0

select person as id,
       sum(case when result = 'W' then 1 else 0 end) as winnercount,
       sum(case when result = 'L' then 1 else 0 end) as losercount
  from (select winner as person, 'W' as result
          from rp_poss
        union all
        select loser, 'L'
          from rp_poss) x
group by person

答案 2 :(得分:0)

既然你提到你有另一张IDs的表,我会在我的解决方案中使用它

SELECT t1.id, COUNT(w.id), COUNT(l.id) 
FROM TableOfIDs t
LEFT JOIN YourTable w ON t.id = w.id
LEFT JOIN YourTable l ON i.id = l.id
GROUP BY t1.id

这样您就可以简化查询。

如果其他表中的ID比Winner / Looser表中的ID多,我们可以使用HAVING子句消除不必要的零。

HAVING COUNT(w.id)+COUNT(i.id) > 0

答案 3 :(得分:0)

试试这个

SELECT ID ,Coalesce(Winners,0),Coalesce(Loosers,0)
FROM (
        SELECT ID , 
                    ( SELECT Count(Winner) FROM rp_poss WHERE WINNER=A.ID GROUP BY Winner ) Winners,
                    ( SELECT Count(Looser) FROM rp_poss WHERE Looser=A.ID GROUP BY Looser ) Loosers                     
        FROM rp_poss A
) result
WHERE Winners > 0 OR Loosers > 0