SELECT id,stadium,team1,team2
FROM game where id =1012
我們可以利用JOIN來同時進行以上兩個步驟。 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 JOIN goal ON teamid ='GER'and id = matchid
使用上題相同的 JOIN語句, 列出球員名字叫Mario (player LIKE ‘Mario%’)有入球的 隊伍1 team1, 隊伍2 team2 和 球員名 player
select team1,team2,player
from game join goal on player like'Mario%'and id = matchid
select matchid,mdate,count(player)from goal join game on id = matchid and teamid ='ger'where team1='ger'or team2 ='ger'groupby matchid,mdate
List every match with the goals scored by each team as shown. This will use “CASE WHEN” which has not been explained in any previous exercises. mdate team1 score1 team2 score2 1 July 2012 ESP 4 ITA 0 10 June 2012 ESP 1 ITA 1 10 June 2012 IRL 1 CRO 3 Notice in the query given every goal is listed. If it was a team1 goal then a 1 appears in score1, otherwise there is a 0. You could SUM this column to get a count of the goals scored by team1. Sort your result by mdate, matchid, team1 and team2.
SELECT mdate,
team1,sum(CASEWHEN teamid=team1 THEN1ELSE0END) score1,
team2,sum(CASEWHEN teamid=team2 THEN1ELSE0END)score2
FROM game JOIN goal ON matchid = id
groupby mdate,matchid,team1,team2
ORDERBY mdate
查出来的结果跟原答案有一点出入,还未知是什么原因
6.2 总结
函数
用法说明
join on
把来自两个或多个表的行结合起来,基于这些表之间的共同字段。简单地说,就是先确定一个主表作为结果集,然后把其他表的行有选择性地“连接”在主表结果集上。格式:表名1 join 表名2 on 条件