MySQL 多表查询,内连接,外连接,联合查询
程序员文章站
2022-05-29 21:31:47
...
#多表链接(隐式内连接)
SELECT user_name,gname,score
FROM users,game,score
WHERE users.`user_qq`= score.`user_qq`
AND game.`gon`= score.`gon`
#内连接 如果没有对应的信息 则不显示
/*语法:
select 列名 from 表1 inner join 表2
on 表1.列名= 表2.列名
inner join 表3
on 表3.列名 = 表2.列名(列名:类型、属性相等)
*/
SELECT user_name AS '玩家昵称',gname AS '游戏名称',score AS '分数'
FROM users INNER JOIN score
ON users.`user_qq`= score.`user_qq`
INNER JOIN game
ON game.`gon`= score.`gon`
#查询每个玩家的昵称、总分和平均分
SELECT user_name AS '昵称',SUM(score) AS '总分',AVG(score) AS '平均分'
FROM users INNER JOIN score
ON users.`user_qq` = score.`user_qq`
GROUP BY users.`user_qq`,users.user_name
#查询平均分数大于3500的分数信息,显示玩家昵称,总分数、平均数,并按照降序排列
SELECT user_name AS '名字',SUM(score) AS '总分',AVG(score) AS '平均分'
FROM users INNER JOIN score
ON users.`user_qq`= score.`user_qq`
GROUP BY users.`user_qq`
HAVING AVG(score)>8700
ORDER BY AVG(score) DESC
#外连接 保证基础表内容全部出现
/*语法:
select 列名1,列名2 from 表1 left join 表2
on 表1.列名 = 表2.列名 (列名:类型、属性相等)
*/
#查询所有玩家关于5号游戏的分数信息
SELECT user_name,score,gon
FROM users LEFT JOIN score
ON users.`user_qq` = score.`user_qq`
AND gon = 5
#子查询 in 、not in
#没有参加
SELECT u.user_qq,u.user_name,s.gon FROM users u ,score s
WHERE u.user_qq
NOT IN(SELECT user_qq FROM score WHERE gon = 5)
#联合查询 纵向拼接查询数据
#语法:查询1 union all 查询2 union all 查询3....
#查询qq号是“11103”的玩家所有分数并计算出总分、平均分数,并显示到同一结果集中
SELECT * FROM score WHERE user_qq = 11101
UNION ALL
SELECT '总分',' ',SUM(score),' ' FROM score WHERE user_qq = 11101
UNION ALL
SELECT '平均分',' ',AVG(score),' ' FROM score WHERE user_qq = 11101
上一篇: mysql多表查询