Home  >  Article  >  Database  >  How can we simulate a MySQL INTERSECT query that returns multiple expressions?

How can we simulate a MySQL INTERSECT query that returns multiple expressions?

王林
王林forward
2023-09-20 09:09:021192browse

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

Since we cannot use INTERSECT query in MySQL, we will use EXIST operator to simulate INTERSECT query. It can be understood through the following example-

Example

In this example we have two tables i.e. Student_detail and Student_info with the following data-

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)

Now, the following query using EXIST operator with WHERE clause will simulate INTERSECT to return "studentid", name, address (where name is not "Yashpal") that exists in both tables -

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)

The above is the detailed content of How can we simulate a MySQL INTERSECT query that returns multiple expressions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete