12 Connection query

1. FROM clause for multi-table query
(1) Multi-table connection
 
Example: query score information, display player nickname, game name, score

SELECT
user_name AS 'nickname',
Gname AS 'Game Name',
score AS 'score'
FROM users,games,scores
WHERE users.user_qq = scores.user_qq #QQ numbers are the same to match
AND games.GNO = scores.GNO #GNO is the same to match

2. Inner join
Features: (1) The status of the two connected tables is equal
(2) If there is no corresponding data in one table in another table, no connection is made.
Example: query score information, player name

SELECT
user_name,score
FROM users,scores
WHERE users.user_qq = scores.user_qq #Inner join matching conditions

Multiple table names appear directly after the FROM clause. This connection method is an inner join, which is an implicit inner join.
3. Display Intralink
grammar:
SELECT col_list
FROM table1 [INNER]JOIN table2
ON table1.col = table2.col #Connection condition
Note: Explicit inner join is faster than implicit inner join operation
Example 1: Query score information, display player nickname, game name, score

SELECT user_name AS 'nickname',
Gname AS 'Game Name',
score AS 'score'
FROM games INNER JOIN scores
ON games.GNO = scores.GNO
INNER JOIN users
ON scores.user_qq = users.user_qq

示例2:查询每个玩家的昵称、总分、平均分

SELECT users.user_qq AS 'QQ',
user_name AS '玩家昵称',
sum(score) AS '总分',
avg(score) AS '平均分'
FROM users INNER JOIN scores
ON users.user_qq = scores.user_qq
GROUP BY users.user_qq , users.user_name

注:当字段在两个表中同时存在时,查询字段时需声明所查询的是哪个表中的字段,如users.user_qq。
示例3:查询平均分数大于300的分数信息,显示玩家昵称、总分数、平均分数,并按照平均分数降序排列

SELECT user_name,
sum(score) AS '总分数',
avg(score) AS '平均分数'
from users inner join scores
on users.user_qq = scores.user_qq
group by users.user_qq ,users.user_name
having avg(score)>300
order by avg(score) asc

4.外连接
特点:
(1)做连接的两个表地位不平等,其中一张是基础表
(2) 基础表中的每条数据必须出现,及时另一张表中没有数据与之匹配,也要用null补齐
(3)左外连接时左表是基础表,右外连接时右表是基础表
(4)语句中,先出现的为左表,后出现的为右表
语法:
SELECT col_list
FROM table1 LEFT|RIGHT [OUTER] JOIN table2
ON table1.col = table2.col
示例1:查询所有玩家关于1号游戏的分数信息

SELECT user_name AS "昵称",
GNO AS "游戏编号",
score AS "分数"
FROM users LEFT JOIN scores
ON users.user_qq = scores.user_qq
AND scores.GNO = 1

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324860204&siteId=291194637