2014-12-20 97 views
1

我有兩張桌子,一個足球比賽,一個進球。我試圖在兩人之間進行左連接的選擇,計算主客場進球數。表是這樣的:MySQL左加入和組

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 

這應該帶回一行與球隊的得分,這可能BA正整數或0(或null)。

到目前爲止,我未能實現這一點 - 如果沒有進球,沒有任何排隊被返回。我究竟做錯了什麼?!任何幫助非常感謝(或鏈接到其他問題 - 我已經看了很多,但沒有找到我設法適應)。

謝謝!

託比

+0

張貼了一份sqlfiddle和期望結果 – Strawberry

回答

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; 
+0

我認爲這正是我想要的,簡單 - 偉大的東西,謝謝! – toby1kenobi

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

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