Skip to main content
  1. Tutorial/

MySQL Join连接类型

232 words·2 mins
MySQL
Table of Contents

Join Type
#

Inner Join
#

SELECT column_name(s) FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name;

Left Join
#

SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name;

Right Join
#

SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name;

Full Join
#

SELECT column_name(s) FROM table1 FULL OUTER JOIN table2 ON table1.column_name = table2.column_name WHERE condition;

GROUP BY
#

GROUP BY语句将具有相同值的行分组为汇总行,例如“查找每个国家/地区的客户数量”。
该GROUP BY语句通常与聚合函数 ( COUNT(), MAX(), MIN(), SUM(), AVG()) 一起使用, 以按一列或多列对结果集进行分组。

SELECT column_name(s) FROM table_name WHERE condition GROUP BY column_name(s) ORDER BY column_name(s);

列出了每个国家的客户数量,从高到低排序:

SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country ORDER BY COUNT(CustomerID) DESC;

group bydistinct 去重

单列去重,结果一样

SELECT DISTINCT `name` FROM user_info;
SELECT `name` FROM user_info GROUP BY name;

多列去重

SELECT DISTINCT `name`,number FROM user_info;
SELECT `name`,number FROM user_info GROUP BY `name`,number;

对于单列或多列去重,使用 group bydistinct 结果是相同的

执行方式

  • distinct 主要是对数据两两进行比较,需要遍历整个表
  • group by 是在查询时先把数据按照分组字段分组出来再查询,当数据量较大时,group by 速度要优于 distinct

Having
#

列出了每个国家的客户数量,从高到低排序(仅包括客户超过 5 个的国家)

SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country HAVING COUNT(CustomerID) > 5 ORDER BY COUNT(CustomerID) DESC;

EXISTS
#

返回 TRUE 并列出产品价格等于 22 的供应商:

SELECT SupplierName FROM Suppliers WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID = Suppliers.supplierID AND Price = 22);

USING连接
#

USING 就是等值连接的一种简化形式,SQL99 中新增的。

当我们进行连接的时候,可以用USING指定数据表里的同名字段进行等值连接。

SELECT  player_id,  team_id,  player_name,  height,  team_name  FROM  player  JOIN  team  USING(team_id) 

同时使用 JOIN USING 可以简化 JOIN ON 的等值连接,它与下面的SQL查询结果是相同的:

SELECT  player_id,  player.team_id,  player_name,  height,  team_name  FROM  player  JOIN  team  ON  player.team_id  =  team.team_id 

Related

MySQL Index
511 words·3 mins
MySQL
MySQL数据库索引 # 一、索引的概念 # 1.
MySQL慢查询治理
288 words·2 mins
MySQL
慢查询 # SQL都需要消耗一定的I/O资源,SQL执行的快慢直接决定了资源被占用时间的长短。
HTTPS 证书申请步骤
44 words·1 min
Network
HTTPS 证书更新 # OHTTPS的免费版证书是由Let’s Encrypt颁发,专业版证书是由Sectigo(原Comodo)颁发。
Docker 日志清理
216 words·2 mins
docker
查看容器文件夹占用 # du -d1 -h /var/lib/docker/containers | sort -h 查询正在运行的Docker, 不建议对正在运行的容器进行操作
Alertmanager 告警配置
294 words·2 mins
AlertManager
group_wait(default: 30s) # How long to initially wait to send a notification for a group of alerts.