我们如何模拟返回多个表达式的 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)
现在,以下使用 EXIST 运算符和 WHERE 子句的查询将模拟 INTERSECT 以返回同时存在于两个表中的“studentid”、“Name”、“Address”,其中名称不为“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 <> 'Yashpal' 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)
广告