1)3种连接
完全外部连接:所有表都连接,允许null值存在
内连接:
select字段名
from表名1 inner join表名2 on表名1.字段名=表名2.字段名
注意内连接inner可以省略,直接使用join默认为内连接
(剔除含有空值的行)
左连接:
select字段名
from表名1 left join表名2 on表名1.字段名=表名2.字段名
(剔除左边空白的行)
右连接:
from表名1 right join表名2 on表名1.字段名=表名2.字段名
2)练习
例:查询有球员名叫Mario进球的队伍1(team1),队伍2(team2)及球员姓名
select team1,team2,player from game inner join goal on game.id=goal.matchid
where player like'%Mario%'
例:查询队伍1(team1)的教练是“Fernando Santos”的球队名称、比赛日期和赛事编号
select mdate,teamname
from game join eteam on game.team1=eteam.id
where coach='Fernando Santos'
表格也可以别名代表原本的表
例:from game ga join eteam et on ga.team1=et.id
多表连接时字段名不唯一时一定要指明表名
例:查询至少出演过第1主角30次的演员名
select name from actor ac join casting ca on ac.id=ca.actorid
where ord=1
group by name
having count(name)>=30
也可以是count(movieid)
例:查询在比赛前十分钟有进球纪录的球员,他的队伍编号、教练、进球时间
select teamid,coach,gtime
from goal join eteam on goal.teamid=eteam.id
where goal.gtime<10
例:查询每场比赛,每个球队的得分情况,按照以下格式显示
最后按照举办时间(mdate) 、赛事编号(matchid) 、队伍1 (team1)和队伍2 (team2)排序
select mdate,team1
,sum(case when team1=teamid then 1 else 0 end) score1
,team2
,sum(case when team2=teamid then 1 else 0 end) score2
from
game join goal on game.id=goal.matchid
group by mdate,team1,team2
order by mdate,matchid,team1,team2
非聚合字段全部要作为group by分组依据