如何双重加入sql查询?
Posted
技术标签:
【中文标题】如何双重加入sql查询?【英文标题】:How to double join the sql query? 【发布时间】:2021-10-12 03:37:26 【问题描述】:我已经构建了这个 sql 查询,它在 phpmyadmin 和 codeigniter 上运行良好;
SELECT teams.team_name,
COUNT(matches.winner) AS win
FROM matches
RIGHT JOIN teams ON teams.team_name = matches.winner
GROUP BY teams.team_name, matches.winner
ORDER BY win DESC
输出:
| team_name | win |
------------------------------
| India | 1 |
| Australia | 4 |
| England | 1 |
| South Africa | 0 |
但我需要以下输出:(还有另一列“loser”)因此我需要对“loser”列应用相同的查询,类似于我对“win”列所做的查询。
预期输出:
| team_name | win | loss
------------------------------
| India | 1 | 2
| Australia | 4 | 3
| England | 1 | 1
| South Africa | 0 | 2
【问题讨论】:
样本数据和预期结果会有所帮助,请阅读Minimal, Reproducible Example 【参考方案1】:一种方法是关联子查询:
SELECT t.team_name,
(SELECT COUNT(*)
FROM matches m
WHERE t.team_name = m.winner
) as num_wins,
(SELECT COUNT(*)
FROM matches m
WHERE t.team_name = m.loser
) as num_loses
FROM matches t
ORDER BY num_wins DESC;
【讨论】:
以上是关于如何双重加入sql查询?的主要内容,如果未能解决你的问题,请参考以下文章