MySQL离开了join和group by

时间:2014-12-20 07:38:00

标签: mysql join left-join

我有两张桌子,一张足球比赛,一张进球。我正在尝试选择两者之间的左联盟,计算主场和客场进球的数量。表格是这样的:

CREATE TABLE `matches` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `home_team_id` int(11) NOT NULL,
    `away_team_id` int(11) NOT NULL
    ...

CREATE TABLE `match_goals` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `match_id` int(11) NOT NULL,
    `team_id` int(11) NOT NULL,
    `minute` int(11) NOT NULL
    ...

并且要添加所有主队的目标,我想做这样的事情:

SELECT * 
FROM 
    (SELECT id, home_team_id, away_team_id from matches) m, 
    (SELECT count(*) AS score, match_id, team_id from match_goals group by match_id, team_id) g 
WHERE m.home_team_id = g.team_id
ORDER by m.id

这应该带回团队得分的一行,可以是正整数或0(或null)。

到目前为止,我未能实现这一点 - 如果没有得分,则不会返回任何行。我究竟做错了什么?!任何帮助都非常感激(或链接到其他问题 - 我已经看了很多,但没有找到任何我设法适应的)。

谢谢!

托比

3 个答案:

答案 0 :(得分:1)

对于相关子查询,这可能是最简单的,而不是显式的left join

select m.*,
       (select count(*)
        from match_goals mg
        where mg.match_id = m.id and mg.team_id = m.home_team_id
       ) as home_goals,
       (select count(*)
        from match_goals mg
        where mg.match_id = m.id and mg.team_id = m.away_team_id
       ) as away_goals
from matches m;

答案 1 :(得分:0)

尝试,

select m.id match_id, home_team_goal, away_team_goal
from matches m left join 
 ( select team_id, match_id, count(*) as home_team_goal
   from match_goals
   group by match_id,team_id
 ) hg on m.id=hg.match_id and m.home_team_id=hg.team_id
  left join 
 ( select team_id, match_id, count(*) as away_team_goal
   from match_goals
   group by match_id,team_id
 ) ag on m.id=ag.match_id and m.away_team_id=ag.team_id

Working SQLFiddle Demo

答案 2 :(得分:0)

如果我们查看SQL left join syntax

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;

如果你想让主场和客场球队得分,你需要做2次加入。

只有主队得分,您的查询才会显示如下:

Select * 
FROM matches as m
LEFT JOIN ( 
   SELECT match_id, team_id, count(*) as count
     from match_goals
   GROUP BY match_id,team_id) as mg)

ON m.id = mg.match_id and m.home_team_id = mg.team_id