MySQL - LEFT JOIN 左连接
与提供两个表交集值的内连接不同,还有另一种类型的连接,称为外连接。此外连接在多种情况下提供两个表中匹配和不匹配记录的集合。
MySQL 左连接
LEFT JOIN 左连接 是一种外连接,它从第一个表检索所有记录,并将它们与第二个表中的记录进行匹配。
如果左表中的记录在第二个表中没有对应记录,则添加 NULL 值。
但是,如果第一个表中的记录数少于第二个表中的记录数,则第二个表中在第一个表中没有对应记录的记录将从结果中丢弃。

语法
以下是 MySQL 中左连接的基本语法 -
SELECT table1.column1, table2.column2... FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name;
示例
使用以下查询,创建一个名为 CUSTOMERS 的表,其中包含客户的个人信息,包括姓名、年龄、地址和工资。
CREATE TABLE CUSTOMERS ( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25), SALARY DECIMAL (18, 2), PRIMARY KEY (ID) );
现在使用 INSERT 语句将值插入到该表中,如下所示 -
INSERT INTO CUSTOMERS VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00), (2, 'Khilan', 25, 'Delhi', 1500.00), (3, 'Kaushik', 23, 'Kota', 2000.00), (4, 'Chaitali', 25, 'Mumbai', 6500.00), (5, 'Hardik', 27, 'Bhopal', 8500.00), (6, 'Komal', 22, 'Hyderabad', 4500.00), (7, 'Muffy', 24, 'Indore', 10000.00);
该表将创建为 −
ID | NAME | AGE | ADDRESS | SALARY |
---|---|---|---|---|
1 | Ramesh | 32 | Ahmedabad | 2000.00 |
2 | Khilan | 25 | Delhi | 1500.00 |
3 | Kaushik | 23 | Kota | 2000.00 |
4 | Chaitali | 25 | Mumbai | 6500.00 |
5 | Hardik | 27 | Bhopal | 8500.00 |
6 | Komal | 22 | Hyderabad | 4500.00 |
7 | Muffy | 24 | Indore | 10000.00 |
让我们创建另一个表 ORDERS,其中包含已下订单的详细信息及其下单日期。
CREATE TABLE ORDERS ( OID INT NOT NULL, DATE VARCHAR (20) NOT NULL, CUSTOMER_ID INT NOT NULL, AMOUNT DECIMAL (18, 2) );
使用 INSERT 语句,将值插入此表,如下所示 -
INSERT INTO ORDERS VALUES (102, '2009-10-08 00:00:00', 3, 3000.00), (100, '2009-10-08 00:00:00', 3, 1500.00), (101, '2009-11-20 00:00:00', 2, 1560.00), (103, '2008-05-20 00:00:00', 4, 2060.00);
表显示如下 −
OID | DATE | CUSTOMER_ID | AMOUNT |
---|---|---|---|
102 | 2009-10-08 00:00:00 | 3 | 3000.00 |
100 | 2009-10-08 00:00:00 | 3 | 1500.00 |
101 | 2009-11-20 00:00:00 | 2 | 1560.00 |
103 | 2008-05-20 00:00:00 | 4 | 2060.00 |
左连接查询:
使用以下左连接查询,我们将检索在指定日期下订单的客户的详细信息。如果没有找到匹配项,则以下查询将在该记录中返回 NULL。
SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS LEFT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
输出
连接后的结果集如下所示:-
ID | NAME | AMOUNT | DATE |
---|---|---|---|
1 | Ramesh | NULL | NULL |
2 | Khilan | 1560.00 | 2009-11-20 00:00:00 |
3 | Kaushik | 1500.00 | 2009-10-08 00:00:00 |
3 | Kaushik | 3000.00 | 2009-10-08 00:00:00 |
4 | Chaitali | 2060.00 | 2008-05-20 00:00:00 |
5 | Hardik | NULL | NULL |
6 | Komal | NULL | NULL |
7 | Muffy | NULL | NULL |
使用 Left Join 连接多个表
Left Join 也可以连接多个表,其中第一个表作为完整表返回,而后面的表则与第一个表中的行匹配。如果记录不匹配,则返回 NULL。
语法
使用 Left Join 连接多个表的语法如下 -
SELECT column1, column2, column3... FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name LEFT JOIN table3 ON table2.column_name = table3.column_name . . .
示例
为了演示多表左连接,我们以之前创建的表 CUSTOMERS 和 ORDERS 为例。除此之外,我们还将创建另一个名为 EMPLOYEE 的表,该表包含组织中员工的详细信息及其销售额,使用以下查询 -
CREATE TABLE EMPLOYEE ( EID INT NOT NULL, EMPLOYEE_NAME VARCHAR (30) NOT NULL, SALES_MADE DECIMAL (20) );
现在,我们可以使用 INSERT 语句将值插入到这个空表中,如下所示 -
INSERT INTO EMPLOYEE VALUES (102, 'SARIKA', 4500), (100, 'ALEKHYA', 3623), (101, 'REVATHI', 1291), (103, 'VIVEK', 3426);
该表创建为 −
EID | EMPLOYEE_NAME | SALES_MADE |
---|---|---|
102 | SARIKA | 4500 |
100 | ALEKHYA | 3623 |
101 | REVATHI | 1291 |
103 | VIVEK | 3426 |
左连接查询:
我们使用下面给出的左连接查询来连接这三个表 -
SELECT CUSTOMERS.ID, CUSTOMERS.NAME, ORDERS.DATE, EMPLOYEE.EMPLOYEE_NAME FROM CUSTOMERS LEFT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID LEFT JOIN EMPLOYEE ON ORDERS.OID = EMPLOYEE.EID;
输出
结果表如下 -
ID | NAME | DATE | EMPLOYEE_NAME |
---|---|---|---|
1 | Ramesh | NULL | NULL |
2 | Khilan | 2009-11-20 00:00:00 | REVATHI |
3 | Kaushik | 2009-10-08 00:00:00 | ALEKHYA |
3 | Kaushik | 2009-10-08 00:00:00 | SARIKA |
4 | Chaitali | 2008-05-20 00:00:00 | VIVEK |
5 | Hardik | NULL | NULL |
6 | Komal | NULL | NULL |
7 | Muffy | NULL | NULL |
使用 WHERE 子句进行左连接
要过滤连接两个表后的记录,可以使用 WHERE 子句。
语法
使用 WHERE 子句的左连接语法如下 -
SELECT column_name(s) FROM table_name1 LEFT JOIN table_name2 ON table_name1.column_name = table_name2.column_name WHERE condition
示例
可以使用 WHERE 子句过滤合并后的数据库表中的记录。考虑前两个表 CUSTOMERS 和 ORDERS;并使用左连接查询将它们连接起来,并使用 WHERE 子句添加一些约束。
SELECT ID, NAME, DATE, AMOUNT FROM CUSTOMERS LEFT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID WHERE ORDERS.AMOUNT > 2000.00;
输出
输出结果为 − −
ID | NAME | DATE | AMOUNT |
---|---|---|---|
3 | Kaushik | 2009-10-08 00:00:00 | 3000.00 |
4 | Chaitali | 2008-05-20 00:00:00 | 2060.00 |
使用客户端程序进行左连接
我们也可以使用客户端程序对一个或多个表执行左连接操作。
语法
要在 PHP 程序中使用左连接来连接两个表,我们需要使用 mysqli 函数 query() 执行带有 LEFT JOIN 子句的 SQL 查询,如下所示 -
$sql = 'SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count FROM tutorials_tbl a LEFT JOIN tcount_tbl b ON a.tutorial_author = b.tutorial_author'; $mysqli->query($sql);
要通过 JavaScript 程序使用左连接来连接两个表,我们需要使用 mysql2 库的 query() 函数执行带有 LEFT JOIN 子句的 SQL 查询,如下所示 -
sql = "SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count FROM tutorials_tbl a LEFT JOIN tcount_tbl b ON a.tutorial_author = b.tutorial_author"; con.query(sql);
要通过 Java 程序使用左连接来连接两个表,我们需要使用 JDBC 函数 executeQuery() 执行带有 LEFT JOIN 子句的 SQL 查询,如下所示 -
String sql = "SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count FROM tutorials_tbl a LEFT JOIN tcount_tbl b ON a.tutorial_author = b.tutorial_author"; st.executeQuery(sql);
要通过 Python 程序使用左连接连接两个表,我们需要使用 MySQL Connector/Python 的 execute() 函数执行带有 LEFT JOIN 子句的 SQL 查询,如下所示 -
left_join_query = "SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS LEFT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUST_ID" cursorObj.execute(left_join_query)
示例
以下是程序 -
$dbhost = 'localhost'; $dbuser = 'root'; $dbpass = 'password'; $dbname = 'TUTORIALS'; $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); if ($mysqli->connect_errno) { printf("Connect failed: %s
", $mysqli->connect_error); exit(); } // printf('Connected successfully.
'); $sql = 'SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count FROM tutorials_tbl a LEFT JOIN tcount_tbl b ON a.tutorial_author = b.tutorial_author'; $result = $mysqli->query($sql); if ($result->num_rows > 0) { echo " following is the both table details after executing left join! "; while ($row = $result->fetch_assoc()) { printf( "Id: %s, Author: %s, Count: %d", $row["tutorial_id"], $row["tutorial_author"], $row["tutorial_count"] ); printf(" "); } } else { printf('No record found.
'); } mysqli_free_result($result); $mysqli->close();
输出
获得的输出如下 -
following is the both table details after executing left join! Id: 1, Author: John Poul, Count: 0 Id: 2, Author: Abdul S, Count: 0 Id: 3, Author: Sanjay, Count: 1 Id: 101, Author: Aman kumar, Count: 0 Id: 102, Author: Sarika Singh, Count: 0
var mysql = require("mysql2"); var con = mysql.createConnection({ host: "localhost", user: "root", password: "password", }); //连接到 MySQL con.connect(function (err) { if (err) throw err; // console.log("Connected successfully...!"); // console.log("--------------------------"); sql = "USE TUTORIALS"; con.query(sql); //left join sql = "SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count FROM tutorials_tbl a LEFT JOIN tcount_tbl b ON a.tutorial_author = b.tutorial_author"; con.query(sql, function (err, result) { if (err) throw err; console.log(result); }); });
输出
生成的输出如下 -
[ { tutorial_id: 1, tutorial_author: 'John Poul', tutorial_count: 2 }, { tutorial_id: 2, tutorial_author: 'Abdul S', tutorial_count: null }, { tutorial_id: 101, tutorial_author: 'Aman kumar', tutorial_count: null }, { tutorial_id: 102, tutorial_author: 'Sarika Singh', tutorial_count: null } ]
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class LeftJoin { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/TUTORIALS"; String username = "root"; String password = "password"; try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection connection = DriverManager.getConnection(url, username, password); Statement statement = connection.createStatement(); System.out.println("Connected successfully...!"); //MySQL LEFT JOIN...!; String sql = "SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count FROM tutorials_tbl a LEFT JOIN tcount_tbl b ON a.tutorial_author = b.tutorial_author"; ResultSet resultSet = statement.executeQuery(sql); System.out.println("Table records after LEFT Join...!"); while (resultSet.next()){ System.out.println(resultSet.getString(1)+ " "+ resultSet.getString(2)+" "+resultSet.getString(3)); } connection.close(); } catch (Exception e) { System.out.println(e); } } }
输出
获得的输出如下所示 -
Connected successfully...! Table records after LEFT Join...! 1 John Paul 1 2 Abdul S null 3 Sanjay 1 4 Sasha Lee null 5 Chris Welsh null
import mysql.connector #建立连接 connection = mysql.connector.connect( host='localhost', user='root', password='password', database='tut' ) cursorObj = connection.cursor() left_join_query = f""" SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS LEFT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUST_ID """ cursorObj.execute(left_join_query) # 获取所有符合条件的行 filtered_rows = cursorObj.fetchall() for row in filtered_rows: print(row) cursorObj.close() connection.close()
输出
以下是上述代码的输出 -
(1, 'Ramesh', None, None) (2, 'Khilan', 1560, '2009-11-20 00:00:00') (3, 'Kaushik', 1500, '2009-10-08 00:00:00') (3, 'Kaushik', 3000, '2009-10-08 00:00:00') (4, 'Chaital', 2060, '2008-05-20 00:00:00') (5, 'Hardik', None, None) (6, 'Komal', None, None) (7, 'Muffy', None, None)