本MySQL教程将通过语法和示例说明了如何实现Mysql相交查询。
尽管MySQL中没有INTERSECT运算符,但是根据INTERSECT查询的特点,可以使用IN子句或EXISTS子句轻松模拟这种类型的查询。
首先,让我们解释什么是INTERSECT查询。INTERSECT查询返回两个或多个数据集的交集。如果两个数据集中都存在一条记录,那么该记录将被包含在INTERSECT结果集中。但是,如果记录仅存在其中一个数据集中,则会将其从INTERSECT结果中省略。
说明: 相交查询将返回蓝色阴影区域中的记录。
SQL中INTERSECT运算符的语法为:
SELECT
expression1, expression2, ... expression_n
FROM
tables
[
WHERE
conditions]
INTERSECT
conditions];
由于无法在MySQL中使用INTERSECT运算符,因此可以使用IN运算符来模拟INTERSECT查询,如下所示:
products.category_id
products
IN
(
inventory.category_id
inventory);
返回产品和库存表之间的都拥有的category_id。
对应的INTERSECT查询语句为:
category_id
inventory;
category_id < 100
inventory
quantity > 0;
下面是在mysql使用IN运算符模拟有筛选条件的相交查询:
products.category_id < 100
AND
inventory.quantity > 0);
在此示例中,添加了WHERE子句,既过滤产品表又过滤库存表的结果。
下面是相交查询时返回多个字段的情况。
contact_id, last_name, first_name
contacts
contact_id < 100
customer_id, last_name, first_name
customers
last_name <>
'Johnson'
;
在Mysql中使用EXISTS子句来模拟相交查询
contacts.contact_id, contacts.last_name, contacts.first_name
contacts.contact_id < 100
EXISTS (
*
customers.last_name <>
customers.customer_id = contacts.contact_id
customers.last_name = contacts.last_name
customers.first_name = contacts.first_name);
使用EXISTS子句返回在contact_id小于100 的contacts表以及last_name不等于Johnson的customers表中都存在的字段数据。
因为我们是进行相交操作,因此需要按以下方式加入相交字段:
customers.first_name = contacts.first_name
这样就确保了两个结果集中都有同样的数据。
原文链接:https://codingdict.com/