首頁  >  文章  >  資料庫  >  我們如何模擬傳回多個表達式的 MySQL INTERSECT 查詢?

我們如何模擬傳回多個表達式的 MySQL INTERSECT 查詢?

王林
王林轉載
2023-09-20 09:09:021239瀏覽

我们如何模拟返回多个表达式的 MySQL INTERSECT 查询?

由於我們無法在MySQL中使用INTERSECT查詢,因此我們將使用EXIST運算子來模擬INTERSECT查詢。可以透過以下範例來理解-

範例

在此範例中,我們有兩個表,即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)

現在,使用具有WHERE 子句的EXIST 運算子的以下查詢將模擬INTERSECT 以傳回兩個表中都存在的「studentid」、姓名、位址(其中名稱不是「Yashpal」) -

mysql>Select Student_detail.studentid,Student_detail.name, student_detail.address FROM student_detail WHERE Student_detail.studentid >100 AND EXISTS (SELECT * FROM Student_info WHERE Student_info.Name <> &#39;Yashpal&#39; AND Student_info.studentid = Student_detail.studentid AND Student_info.name = Student_detail.name);
+-----------+--------+------------+
| studentid | name   | address    |
+-----------+--------+------------+
|       105 | Gaurav | Chandigarh |
|       130 | Ram    | Jhansi     |
|       132 | Shyam  | Chandigarh |
|       133 | Mohan  | Delhi      |
+-----------+--------+------------+
4 rows in set (0.00 sec)

以上是我們如何模擬傳回多個表達式的 MySQL INTERSECT 查詢?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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