MySQL - 右连接



MySQL 右连接

MySQL 中的右连接右外连接查询返回右表中的所有行,即使左表中没有匹配项也是如此。因此,如果在左表中没有匹配到记录,右连接仍将在结果中返回一行,但在左表每一列中值为 NULL。

简而言之,右连接返回右表中的所有值,加上左表中的匹配值,如果连接谓词没有匹配项则为 NULL。

Right Join

实施右连接后显示的结果表不会存储在数据库中的任何位置。

语法

以下是 SQL 中右连接的基本语法:

SELECT table1.column1, table2.column2...
FROM table1
RIGHT JOIN table2
ON table1.common_field = table2.common_field;

示例

假设我们正在创建一个名为 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 姓名 年龄 地址 薪水
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 日期 客户ID 金额
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

右连接查询

现在,让我们使用以下右连接查询连接这两个表。

SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

输出

这将产生以下结果:

ID 姓名 金额 日期
3 Kaushik 3000.00 2009-10-08 00:00:00
3 Kaushik 1500.00 2009-10-08 00:00:00
2 Khilan 1560.00 2009-11-20 00:00:00
4 Chaitali 2060.00 2008-05-20 00:00:00

使用右连接连接多个表

与左连接一样,右连接也连接多个表。但是,区别在于返回的是第二个表而不是第一个表。

语法

以下是使用右连接连接多个表的语法:

SELECT column1, column2, column3...
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name
RIGHT JOIN table3
ON table2.column_name = table3.column_name
.
.
.

示例

在这里,让我们考虑之前创建的 CUSTOMERS 和 ORDERS 表;以及新创建的 EMPLOYEE 表。

我们将使用以下查询创建 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 员工姓名 销售额
102 SARIKA 4500
100 ALEKHYA 3623
101 REVATHI 1291
103 VIVEK 3426

让我们使用以下右连接查询连接这三个表:

SELECT CUSTOMERS.ID, CUSTOMERS.NAME, ORDERS.DATE, EMPLOYEE.EMPLOYEE_NAME
FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
RIGHT JOIN EMPLOYEE
ON ORDERS.OID = EMPLOYEE.EID;

通过此查询,我们试图显示客户 ID、客户姓名、特定日期的订单以及销售这些商品的员工姓名记录。

输出

获得的结果表如下:

ID 姓名 日期 员工姓名
3 Kaushik 2009-10-08 00:00:00 SARIKA
3 Kaushik 2009-10-08 00:00:00 ALEKHYA
2 Khilan 2009-11-20 00:00:00 REVATHI
4 Chaitali 2008-05-20 00:00:00 VIVEK

带有 WHERE 子句的右连接

WHERE 子句用于过滤满足其指定条件的记录。此子句可用于右连接技术,以对获得的结果集应用约束。

语法

与 WHERE 子句一起使用时,右连接的语法如下:

SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2
ON table_name1.column_name = table_name2.column_name
WHERE condition

示例

可以使用 WHERE 子句过滤组合数据库表中的记录。考虑之前的两个表 CUSTOMERS 和 ORDERS;并使用以下查询连接它们:

SELECT ID, NAME, DATE, AMOUNT FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
WHERE ORDERS.AMOUNT > 1000.00;

输出

获得的结果表如下:

ID 姓名 日期 金额
3 Kaushik 2009-10-08 00:00:00 3000.00
3 Kaushik 2009-10-08 00:00:00 1500.00
2 Khilan 2009-11-20 00:00:00 1560.00
4 Chaitali 2008-05-20 00:00:00 2060.00

使用客户端程序进行右连接

我们还可以使用客户端程序对一个或多个表执行右连接操作。

语法

要通过 PHP 程序使用右连接连接两个表,我们需要使用mysqli 函数query()执行带有 RIGHT JOIN 子句的 SQL 查询,如下所示:

$sql = 'SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count FROM tutorials_tbl a RIGHT JOIN tcount_tbl b 
ON a.tutorial_author = b.tutorial_author';
$mysqli->query($sql);

要通过 JavaScript 程序使用右连接连接两个表,我们需要使用mysql2 库的query() 函数执行带有 RIGHT JOIN 子句的 SQL 查询,如下所示:

sql = "SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count FROM tutorials_tbl a RIGHT JOIN tcount_tbl b 
ON a.tutorial_author = b.tutorial_author";
con.query(sql);  

要通过 Java 程序使用右连接连接两个表,我们需要使用JDBC 函数executeQuery()执行带有 RIGHT JOIN 子句的 SQL 查询,如下所示:

String sql = "SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count FROM tutorials_tbl a RIGHT JOIN tcount_tbl b 
ON a.tutorial_author = b.tutorial_author";
st.executeQuery(sql);

要通过 python 程序使用右连接连接两个表,我们需要使用MySQL Connector/Pythonexecute() 函数执行带有 RIGHT JOIN 子句的 SQL 查询,如下所示:

right_join_query = "SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS RIGHT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUST_ID"
cursorObj.execute(right_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 RIGHT 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 right 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 right join!
Id: , Author: , Count: 20
Id: , Author: , Count: 5
Id: , Author: , Count: 4
Id: , Author: , Count: 20
Id: , Author: , Count: 1
Id: 3, Author: Sanjay, Count: 1    
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);

  //Right Join
  sql =
    "SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count FROM tutorials_tbl a RIGHT 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: null, tutorial_author: null, tutorial_count: 20 },
   { tutorial_id: null, tutorial_author: null, tutorial_count: 5 },
   { tutorial_id: null, tutorial_author: null, tutorial_count: 4 },
   { tutorial_id: null, tutorial_author: null, tutorial_count: 20 },
   { tutorial_id: null, tutorial_author: null, tutorial_count: 1 },
   { tutorial_id: null, tutorial_author: null, tutorial_count: 1 },
   { tutorial_id: 1, tutorial_author: 'John Poul', tutorial_count: 2 }
]
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class RightJoin {
   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 RIGHT JOIN...!;
         String sql = "SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count FROM tutorials_tbl a RIGHT 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...!
null null 20
null null 5
null null 4
null null 20
1 John Paul 1
3 Sanjay 1
import mysql.connector
#establishing the connection
connection = mysql.connector.connect(
    host='localhost',
    user='root',
    password='password',
    database='tut'
)
cursorObj = connection.cursor()
right_join_query = f"""
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUST_ID
"""
cursorObj.execute(right_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()         

输出

以上代码的输出如下:

(3, 'kaushik', 3000, '2009-10-08 00:00:00')
(3, 'kaushik', 1500, '2009-10-08 00:00:00')
(2, 'Khilan', 1560, '2009-11-20 00:00:00')
(4, 'Chaital', 2060, '2008-05-20 00:00:00')
广告