如何使用MySQL LEFT JOIN 来模拟MySQL MINUS 查询?

2023年 9月 16日 34.8k 0

如何使用MySQL LEFT JOIN 来模拟MySQL MINUS 查询?

由于我们无法在 MySQL 中使用 MINUS 查询,因此我们将使用 LEFT JOIN 来模拟 MINUS 查询。可以借助以下示例来理解:

示例

在此示例中,我们有两个表,即 Student_detail 和 Student_info,其内容如下数据 -

mysql> Select * from Student_detail;
+-----------+---------+------------+------------+
| studentid | Name    | Address    | Subject    |
+-----------+---------+------------+------------+
| 101       | YashPal | Amritsar   | History    |
| 105       | Gaurav  | Chandigarh | Literature |
| 130       | Ram     | Jhansi     | Computers  |
| 132       | Shyam   | Chandigarh | Economics  |
| 133       | Mohan   | Delhi      | Computers  |
| 150       | Rajesh  | Jaipur     | Yoga       |
| 160       | Pradeep | Kochi      | Hindi      |
+-----------+---------+------------+------------+
7 rows in set (0.00 sec)

mysql> Select * from Student_info;
+-----------+-----------+------------+-------------+
| studentid | Name      | Address    | Subject     |
+-----------+-----------+------------+-------------+
| 101       | YashPal   | Amritsar   | History     |
| 105       | Gaurav    | Chandigarh | Literature  |
| 130       | Ram       | Jhansi     | Computers   |
| 132       | Shyam     | Chandigarh | Economics   |
| 133       | Mohan     | Delhi      | Computers   |
| 165       | Abhimanyu | Calcutta   | Electronics |
+-----------+-----------+------------+-------------+
6 rows in set (0.00 sec)

登录后复制

现在,以下使用 LEFT JOIN 的查询将模拟 MINUS 以返回 Student_info 中的“studentid”值,但不返回 Student_detail 表中的值。

mysql> SELECT studentid from student_info LEFT JOIN Student_detail USING(studentid) WHERE student_detail.studentid IS NULL;
+-----------+
| studentid |
+-----------+
|       165 |
+-----------+
1 row in set (0.07 sec)

登录后复制

现在,以下查询将为我们提供与上述查询相反的结果,即它将返回 Student_detail 中的“studentid”值,但不会返回 Student_info 表中的值。

mysql> SELECT studentid from student_detail LEFT JOIN Student_info USING(studentid) WHERE student_info.studentid IS NULL;
+-----------+
| studentid |
+-----------+
|       150 |
|      160  |
+-----------+
2 rows in set (0.00 sec)

登录后复制

以上就是如何使用MySQL LEFT JOIN 来模拟MySQL MINUS 查询?的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

Oracle如何使用授予和撤销权限的语法和示例
Awesome Project: 探索 MatrixOrigin 云原生分布式数据库
下载丨66页PDF,云和恩墨技术通讯(2024年7月刊)
社区版oceanbase安装
Oracle 导出CSV工具-sqluldr2
ETL数据集成丨快速将MySQL数据迁移至Doris数据库

发布评论