from子句进行多表查询
例如:查询分数信息,显示玩家昵称、游戏名称和分数
select user_name as '昵称',
gname as '游戏名称',
score as '分数'
from users,games,scores
where users.user_qq=scores.user_qq
and games.gno=scores.gno
内连接
连接查询分为内连接和外连接两种
内连接特点:
相连接的两张表地位平等
如果一张表中在另一张表中不存在对应数据,则不做连接
from子句后面直接出现多个表名,这种连接方式即属于内连接,是隐式连接
显示连接:select col_list from table1[inner] join table2 on table1.col=table2.col
显示内连接比隐式内连接相同情况下更快。on是连接条件的限定
例如:查询分数信息,显示玩家昵称、游戏名和分数
select user_name as '玩家昵称',
gname as '游戏名称',
score as '分数'
from games inner join scores
on games.gno=scores.gno
inner join users
on scores.user_qq=users.user_qq
(inner代表内连接, join 大概的意思就是关联,games关联scores在关联users)
例如:查询每个玩家的昵称、总分和平均分
(为users表和scores表添加别名,节省代码量)
select user_name as '玩家昵称',
sum(score) as '总分',
avg(score) as '平均分'
from users u inner join scores s
on u.user_qq=s.user_qq
group by u.user_qq,u.user_name
例如:查询平均分数大于3500的分数信息,显示玩家昵称,总分数、平均分数,并按照分数降序排列
select user_name as '玩家昵称',
sum(score) as '总分',
avg(score) as '平均分'
from users u inner join scores s
on u.user_qq=s.user_qq
group by u.user_qq,u.user_name
having avg(score)>3500
order by avg(score) desc
外连接:
分为左外连接和有外连接
外连接特点:
做连接的两个表地位不相等,其中有一张是基础表
基础表中的每条数据必须出现,即使另外一张表中没有数据与之匹配,也要用Null补齐
左外连接时左表为基础表,右外连接时右表为基础表
语句中先出现的表为‘左表’,后出现的表为‘右表’
select col_list
from table1 left|right|[outer] join table2
on table1.col=table2.col
(left代表左外连接,right代表右外连接)
例如:查询所有玩家关于5号游戏的分数信息
select user_name as '昵称',
gno as '游戏编号',
score as '分数'
from users u left join scores s
on u.user_qq=s.user_qq
and s.gno=5
(如果把left去掉,则变成了内连接,那么没有玩过5号游戏的玩家就不会被显示出来)