分支(branch_name,branch_city,资产)
客户(customer_name,customer_street,customer_city)
贷款(loan_number,branch_name,金额)
借款人(customer_name,loan_number)
帐户(account_number,branch_name,余额)
存款人(customer_name,account_number)
中的“=”,“IN”和“NOT IN”和“MINUS”如何?
select c.customer_name
from Customer c, Borrower b, Loan l
where c.customer_city = 'Fairfax AND c.customer_name = b.customer_name
AND b.loan_number = l.loan_number
minus
select d.customer_name
from Depositer d, Account a
where d.account_number = a.account_number
和
select c.customer_name
from Customer c
where c.customer_city = 'Fairfax' AND c.customer_name in
(select b.customer_name
from Borrower b
where b.loan_number in
(select l.loan_number
from Loan l
where b.customer_name not in
(select d.customer_name
from Account a, Depositor d
where a.account_number = d.account_number)))
彼此不同?他们应该完成同样的事情
答案 0 :(得分:1)
SQL的“乐趣”之一是可以使用各种等效的SQL结构编写相同的关系运算符(交叉,差异等)(这部分解释了为什么SQL优化器并不总是选择最佳计划来自用户的帮助)。
使用这些简单的示例表:
WITH A AS (SELECT * FROM (VALUES (1), (2), (3)) AS T (n)),
B AS (SELECT * FROM (VALUES (3), (4), (5)) AS T (n))
使用IN (<subquery>)
SELECT n
FROM A
WHERE n IN ( SELECT n FROM B ) ;
使用量化比较的交叉点
SELECT n
FROM A
WHERE n = ANY ( SELECT n FROM B ) ;
使用INTERSECT
SELECT n
FROM A
INTERSECT
SELECT n
FROM B;
交叉点使用INTERSECT
,替代语法:
TABLE A
INTERSECT
TABLE B;
使用EXISTS (<subquery>)
SELECT n
FROM A
WHERE EXISTS ( SELECT *
FROM B
WHERE B.n = A.n
);
使用连接的交叉点
SELECT n
FROM A NATURAL JOIN B;
使用MATCH (<subquery>)
SELECT n
FROM A
WHERE n MATCH ( SELECT n FROM B ) ;
使用NOT IN (<subquery>)
SELECT n
FROM A
WHERE n NOT IN ( SELECT n FROM B ) ;
使用量化比较的差异
SELECT n
FROM A
WHERE n <> ALL ( SELECT n FROM B ) ;
使用EXCEPT
[[MINUS
在Oracle中]
SELECT n
FROM A
EXCEPT
SELECT n
FROM B;
使用EXCEPT
的差异,替代语法:
TABLE A
EXCEPT
TABLE B;
使用NOT EXISTS (<subquery>)
SELECT n
FROM A
WHERE NOT EXISTS ( SELECT *
FROM B
WHERE B.n = A.n
);
使用连接的差异
SELECT A.n
FROM A LEFT OUTER JOIN B ON A.n = B.n
WHERE B.n IS NULL;
[SQL没有NOT MATCH
运算符!]
答案 1 :(得分:0)
=
用于与单个值进行比较,而IN
用于与多个值进行比较。 NOT IN
只会相反,即除了这些值之外它等于任何值,MINUS
实际上是从第二个子查询中减去第一个子查询的每个结果。
您可以在此处找到有关MINUS的更多信息:MINUS keyword
答案 2 :(得分:0)
WHERE ... IN ...
允许您搜索值列表,例如:
SELECT * FROM `orders` WHERE `status` IN("placed", "processed", "fulfilled")
这比写这个更容易:
SELECT * FROM `orders` WHERE `status` = "placed" OR `status` = "processed" OR `status` = "fulfilled"
特别是当您不知道可能值的“范围”时,或者您希望将该条件与其他条件相结合时(它会因为有很多括号条件而变得讨厌)。例如:
SELECT * FROM `orders_items` WHERE `order_id` IN (
SELECT `order_id` FROM `orders` WHERE `status` IN ("processed", "fulfilled")
)
很多时候,JOIN
会更合适(例如在上一个示例中),但如果您拥有WHERE ... IN ...
列或预定义的列表,则ENUM
会很好可能的过滤器。
WHERE ... NOT IN ...
是相同的,但是被否定了。
要回答您的实际问题,老实说,我没有时间看看这些查询是如何不同的。如果只是可读性,我更喜欢前者对后者的查询。当你处理主键引用(即INT列)时,我几乎总是赞成JOIN
超过WHERE IN
或WHERE NOT IN
。