0

May I know is there any difference on using AND or EXIST for selecting on 2 tables by composite foreign key?

AND example:

SELECT comp1, comp2 
FROM TABLE1 
WHERE comp1 = ( SELECT comp1 FROM TABLE2 ) 
  AND comp2 = ( SELECT comp2 FROM TABLE2 );

EXISTS example:

SELECT comp1, comp2 
FROM TABLE1 
WHERE EXISTS( SELECT * 
              FROM TABLE2 
              WHERE TABLE1.comp1 = TABLE2.comp1 
                and TABLE1.comp2 = TABLE2.comp2);

Thanks.

4

2 回答 2

4

即使将=更改为IN运算符,第一个也不正确,因为您正在比较单个值而不是值的组合。

使第一个正确,您需要将其重写为:

select comp1, comp2 
from table1
where (comp1, comp2) IN (select comp1, comp2 from table2);

考虑以下示例:

insert into table1 (comp1, comp2) values (1,2);
insert into table1 (comp1, comp2) values (2,1);
insert into table1 (comp1, comp2) values (1,1);
insert into table1 (comp1, comp2) values (2,2);

insert into table2 (comp1, comp2) values (1,1);
insert into table2 (comp1, comp2) values (2,2);

您的第一条语句(使用IN代替时=)将返回 table1 中的所有行,这显然是不正确的。如果您正在比较这两个值的组合,那么我的语句仅从 table1 中正确返回两行。

这是一个 SQLFiddle 示例:http ://sqlfiddle.com/#!4/e3c7a/1

于 2013-11-03T11:25:59.030 回答
1

在第一种情况下,如果出现以下任何情况,您将收到错误:

SELECT comp1 FROM TABLE2
SELECT comp2 FROM TABLE2

会给你超过 1 个值;可能会的。

当结果集的行数大于 0 时,EXISTS 为真,因此第二个看起来是正确的。

于 2013-11-03T11:08:56.493 回答