1.联合查询语法:
SELECT_statement
UNION [ALL] SELECT_statement
[UNION [ALL] SELECT_statement]
[...n]
2.作用和特点
(1)可以把多条查询语句所擦汗恒的结果集纵向连接为一体(纵向:即将字段合并为一列)
(2)有ALL关键字可以显示全部数据(即重复的也显示出来)
(3)列的数量与类型都要兼容(即:匹配的列数目相同,类型兼容)
例1:
SELECT user_name FROM users
UNION
SELECT gname FROM games
例2:查询玩家表中所有女性玩家和生日为空的玩家
SELECT * FROM users WHERE user_sex = "女"
UNION
SELECT * FROM users WHERE user_birthday IS NULL
例3:查询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'
注:'总分',' ',两列是为了满足联合查询在”数量匹配“上的要求。