我想不使用INNER JOIN来构造查询。我发现这样的内在:
Select A.Name
from A INNER JOIN B on (A.id1 = B.id1 AND A.id2 = B.id2)
Where B.id = @Id
与以下内容相同:
select A.Name
from A
where
A.id1 in (select B.id1 from B where B.id = @Id)
and
A.id2 in (select B.id2 from B where B.id = @Id)
不是吗?
请注意,我的问题不是关于它是否更好,仅当它等于或不等于该INNER时。
答案 0 :(得分:3)
您的第二个查询可能匹配来自不同B行的id1和id2,因此查询可能返回不期望的行。您必须将id1和id2放在一起:
使用EXISTS
:
select A.Name
from A
where exists (select * from B
where A.id1 = B.id1 AND A.id2 = B.id2
and B.id = @Id)
或“行和表的构造函数”
select A.Name
from A
where (A.id1, A.id2) in (select B.id1, B.id2 from B where B.id = @Id)