使用in关键字的子查询
例如:查询游戏类型是“棋牌类”的游戏分数信息
select * from scores gno in
(select gno from games where gtype='棋牌')
子查询一般不写为select * from...,因为*代表多个列,增加了查询量
例如:查询没有参与5号游戏的qq(要从玩家表中查,而不是分数表,因为有的玩家没有玩游戏)
select user_qq from users
where user_qq in
(select user_qq from scores where gno=5)
使用exists关键字的子查询
例如:如果存在昵称为“孙悟空”,则查询分数表中的数据
select * from scores
where exists
(select * form users where user_name='孙悟空')
联合查询
特点是把多条查询语句所产生的结果集纵向连接为一体(all关键字可以把重复的数据显示出来,没有就只显示一个),并且每个查询结果列数要相同,否则会产生不兼容的情况
select_statement
union[all] select_statement
[union[all]select_statement]
[....n]
select user_name from users
union
select gname from games
例如:查询玩家表中所有女性玩家和生日为空的玩家
select * from users where user_sex='女'
union
select * from users where user_birthday is null
传统写法:
select * from users where user_sex='女' or user_birthday is null
例如:查询QQ号是12301玩家的所有分数并计算出总分和平均分数,并显示到同一个结果集中
select user_qq,gno,score from scores where user_qq='12301'
union all
select '总分',' ',sum(score) from scores where user_qq='12301'
union all
select '平均分',' 'avg(score) from scores where user_qq='12301'
其实select关键字之后,可以加上字符串,字符串会被显示在查询结果中,这是为了与第一个查询结果相匹配.