多表查询,内连接(隐式、显示),外连接(左外、右外、基础表)

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号游戏的玩家就不会被显示出来)

 


  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值