参考链接
修改此SQL以列出 賽事編號matchid 和球員名 player ,該球員代表德國隊Germany入球的。要找出德國隊球員,要檢查: teamid = ‘GER’
SELECT matchid, player FROM goal
WHERE teamid LIKE 'GER'
留意在 goal 表格中的欄位 matchid ,是對應表格game的欄位id。我們可以在表格 game中找出賽事1012的資料。
只顯示賽事1012的 id, stadium, team1, team2
SELECT id,stadium,team1,team2
FROM game
WHERE id = 1012
SELECT *
FROM game JOIN goal ON (id=matchid)
語句FROM 表示合拼兩個表格game 和 goal的數據。語句 ON 表示如何找出 game中每一列應該配對goal中的哪一列 – goal的 id 必須配對game的 matchid 。 簡單來說,就是 ON (game.id=goal.matchid)
以下SQL列出每個入球的球員(來自goal表格)和場館名(來自game表格)
修改它來顯示每一個德國入球的球員名,隊伍名,場館和日期。
SELECT player, teamid, stadium, mdate
FROM game ga JOIN goal go ON (ga.id = go.matchid)
WHERE teamid LIKE 'GER'
SELECT team1, team2, player
FROM game ga JOIN goal go ON (ga.id = go.matchid)
WHERE player LIKE 'Mario%'
SELECT player, teamid, coach, gtime
FROM eteam e JOIN goal g ON (e.id = g.teamid)
WHERE gtime < 10
SELECT mdate, teamname
FROM eteam e JOIN game g ON (e.id = g.team1)
WHERE coach = 'Fernando Santos'
SELECT player
FROM game ga JOIN goal go ON (ga.id = go.matchid)
WHERE stadium = 'National Stadium, Warsaw'
SELECT DISTINCT(player)
FROM game ga JOIN goal go ON (ga.id = go.matchid)
WHERE teamid!='GER' AND (team1 = 'GER' OR team2 = 'GER')
SELECT teamname, COUNT(teamid)
FROM goal g JOIN eteam e ON (g.teamid= e.id)
GROUP BY teamname
SELECT stadium, COUNT(player)
FROM game ga JOIN goal go ON (ga.id= go.matchid)
GROUP BY stadium
SELECT matchid, mdate, COUNT(teamid)
FROM game ga JOIN goal go ON (ga.id= go.matchid)
WHERE (ga.team1 = 'POL' OR ga.team2 = 'POL')
GROUP BY matchid, mdate
疑问:在使用 GROUP BY + COUNT(teamid) 的时候,需要指定所有的参数
SELECT matchid, mdate, COUNT(teamid)
FROM game ga JOIN goal go ON (ga.id= go.matchid)
WHERE (ga.team1 = 'GER' OR ga.team2 = 'GER') AND teamid = 'GER'
GROUP BY matchid, mdate
SELECT mdate,
team1, SUM(CASE WHEN teamid = team1 THEN 1 ELSE 0 END) score1,
team2, SUM(CASE WHEN teamid = team2 THEN 1 ELSE 0 END) score2
FROM game ga LEFT OUTER JOIN goal go ON (ga.id= go.matchid)
GROUP BY mdate, team1, team2
疑问:这里为什么需要用到 LEFT OUTER JOIN