MySQL - 左连接



与提供两个表交集值的内连接不同,还有另一种类型的连接称为外连接。此外连接在多种情况下提供两个表的匹配和不匹配记录的集合。

MySQL 左连接

左连接是一种外连接,它检索第一个表中的所有记录并将其与第二个表中的记录匹配。

如果左表中的记录在第二个表中没有对应的记录,则会添加 NULL 值。

但是,如果第一个表中的记录数少于第二个表中的记录数,则第二个表中在第一个表中没有任何对应记录的记录将从结果中丢弃。

Left Join

语法

以下是 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

使用左连接连接多个表

左连接还连接多个表,其中第一个表作为整体返回,后续表与第一个表中的行匹配。如果记录不匹配,则返回 NULL。

语法

使用左连接连接多个表的语法如下:

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 程序通过左连接连接两个表,我们需要使用 **execute()** 函数和 **MySQL Connector/Python** 执行带有 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! \n"; while ($row = $result->fetch_assoc()) { printf( "Id: %s, Author: %s, Count: %d", $row["tutorial_id"], $row["tutorial_author"], $row["tutorial_count"] ); printf("\n"); } } 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",
}); //Connecting to 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://127.0.0.1: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
#establishing the connection
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)
# Fetching all the rows that meet the criteria
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)
广告