首頁  >  文章  >  資料庫  >  我們如何模擬 MySQL MINUS 查詢?

我們如何模擬 MySQL MINUS 查詢?

WBOY
WBOY轉載
2023-09-09 14:49:061186瀏覽

我们如何模拟 MySQL MINUS 查询?

由於我們無法在MySQL中使用MINUS查詢,因此我們將使用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)

現在,以下使用JOINS 的查詢將模擬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 MINUS 查詢?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除