MySQL - Left Join

MySQL - Left Join 首页 / MySQL入门教程 / MySQL - Left Join

MySQL中的Left Join用于查询多个表中的记录。该子句类似于可以在FROM关键字之后立即与SELECT语句一起使用的内部联接子句。当无涯教程使用Left Join子句时,它将返回第一个(左侧)表中的所有记录,甚至没有从第二个(右侧)表中找到匹配的记录。如果找不到右侧表中的任何匹配记录,则返回null。

可以通过以下可视化表示来理解它,其中"Left Join"返回左侧表中的所有记录,而仅返回右侧表中的匹配记录:

MySQL LEFT JOIN

LEFT JOIN语法

以下语法说明了Left Join子句以连接两个或多个表:

SELECT columns  
FROM table1  
LEFT [OUTER] JOIN table2  
ON Join_Condition;

在以上语法中, table1 是左侧表,而 table2 是右侧表。此子句根据指定的连接条件(Join_Condition)返回表1中的所有记录和表2中的匹配记录。

让无涯教程举一些例子来了解Left Join或Left Outer Join子句的工作方式:

LEFT JOIN 两个表

在这里,将创建两个表" customers" 和" orders" ,其中包含以下数据:

表:customers

MySQL LEFT JOIN

表:orders

MySQL LEFT JOIN

要从两个表中选择记录,请执行以下查询:

SELECT customers.customer_id, cust_name, price, date
FROM customers
LEFT JOIN orders ON customers.customer_id = orders.customer_id;

成功执行查询后,它将给出以下输出:

MySQL LEFT JOIN

LEFT JOIN 与USING子句

表客customers和orders具有相同的列名,即customer_id。在这种情况下,MySQL Left Join也可以与USING子句一起使用来访问记录。以下语句使用带有USING关键字的Left Join子句返回客户ID(customer_id),客户名称(cust_name),职业(occupation),价格(price)和日期(date)。

SELECT customer_id, cust_name, occupation, price, date
FROM customers
LEFT JOIN orders USING(customer_id);

上面的语句将给出以下输出:

链接:https://www.learnfk.comhttps://www.learnfk.com/mysql/mysql-left-join.html

来源:LearnFk无涯教程网

MySQL LEFT JOIN

LEFT JOIN与Group By子句

Left Join也可以与GROUP BY子句一起使用。下面的语句使用Left Join子句和GROUP BY子句返回客户ID(customer_id),客户名(cust_name),资格(qualification),价格(price)和日期(date)。

SELECT customers.customer_id, cust_name, qualification, price, date
FROM customers
LEFT JOIN orders ON customers.customer_id = orders.customer_id
GROUP BY price;

上面的语句将给出以下输出:

链接:https://www.learnfk.comhttps://www.learnfk.com/mysql/mysql-left-join.html

来源:LearnFk无涯教程网

MySQL LEFT JOIN

Left Join 与 WHERE子句

WHERE子句用于从表中返回过滤器结果。下面的示例使用Left Join子句对此进行说明:

SELECT customer_id, cust_name, occupation, price, date
FROM customers
LEFT JOIN orders 
USING(customer_id) WHERE price>2500;

该语句给出以下结果:

MySQL LEFT JOIN

LEFT JOIN 多个表

无涯教程已经创建了两个名为" customers" 和" orders" 的表。再创建一个表,并将其命名为" contacts",其中包含以下数据:

MySQL LEFT JOIN

执行以下语句以加入三个表的客户,订单和联系人:

SELECT customers.customer_id, cust_name, order_id, price, cellphone
FROM customers
LEFT JOIN contacts ON customer_id = contact_id
LEFT JOIN orders ON customers.customer_id = orders.customer_id ORDER BY income;

成功执行以上查询后,将给出以下输出:

MySQL LEFT JOIN

 LEFT JOIN 与 ON子句

在Left Join中,条件WHERE和ON给出不同的结果。无涯教程可以查看以下查询以了解它们之间的差异:

WHERE子句

SELECT cust_name, occupation, order_id, price, date
FROM customers
LEFT JOIN orders 
USING(customer_id) WHERE price=2500;

它将返回以下输出:

MySQL LEFT JOIN

ON 子句

SELECT cust_name, occupation, order_id, price, date
FROM customers LEFT JOIN orders ON price=2500;

它将给出以下输出:

MySQL LEFT JOIN

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

从0开始学架构 -〔李运华〕

从0开始学大数据 -〔李智慧〕

玩转Spring全家桶 -〔丁雪丰〕

高并发系统设计40问 -〔唐扬〕

系统性能调优必知必会 -〔陶辉〕

正则表达式入门课 -〔涂伟忠〕

重学线性代数 -〔朱维刚〕

Kubernetes入门实战课 -〔罗剑锋〕

AI大模型之美 -〔徐文浩〕

好记忆不如烂笔头。留下您的足迹吧 :)