开发者

SQL query that returns columns form table A plus a bit column that specifies whether the PK of table A exists in table B

开发者 https://www.devze.com 2022-12-31 11:48 出处:网络
How can I write an efficient SQL query that returns columns form table A plus a bit column that specifies whether the PK of table A exists in table B? I am using MS SQLServer 2005. T开发者_JAVA百科han

How can I write an efficient SQL query that returns columns form table A plus a bit column that specifies whether the PK of table A exists in table B? I am using MS SQLServer 2005. T开发者_JAVA百科hanks.


It depends if the foreign table relationship is 1:1 or 1:Many. If is 1:1 the you can use a normal join:

select A.*, case when b.id is null then 0 else 1 end
from A 
left join B on A.id = B.id;

If the relation is 1:Many then the join would multiply the result, so you have to restrict it, and there are several ways. A simple way is using outer apply and top:

select A.*, case when b.id is null then 1 else 0 end
from A
outer apply (
 select top (1) id from B where A.id = B.id) as b;

As for performance, almost all solution proposed will perform the same, provided there is an appropriate index on B(id) in place.


The other answers specify a correlated subquery; a (left outer) join is likely more efficient.

I'll assume that b.fk is the foreign key in b to a's pk.

select 
   a.*, 
   case when b.fk is not null then 1 else 0 end as exists_in_b
from 
   a 
   left outer join b on (a.id = b.fk ) 
;


I'm assuming that the primary key in table A is called PK and that the column in B that would contain this key is also called PK.

SELECT A.*, CASE WHEN EXISTS (SELECT 1 FROM B WHERE B.PK = A.PK) THEN 1 ELSE 0 END
FROM A

Efficiency of this query will depend on the indexing in table B -- specifically, whether column PK is indexed.

I dislike SELECT * in general, but for this example, it serves the purpose.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号