sql join告诉我其他表中是否存在ID

时间:2011-12-07 16:08:58

标签: sql join

我有两张桌子:

 A      B
 --    ----
 ID    FKID
 --    ----
 1      3
 2      3   
 3      4
 4      4

我需要一个select语句,它向我显示A的所有字段,该字段告诉我表B是否有任何与该ID匹配的id。

Desired Result
-----------
 ID | hasB
-----------
 1    no
 2    no    
 3    yes
 4    yes

6 个答案:

答案 0 :(得分:11)

在SQL Server中,这将是最有效的方式,而不是OUTER JOIN然后使用DISTINCT删除重复项。不确定postgres,你需要检查计划。

SELECT ID,
       CASE
         WHEN EXISTS (SELECT *
                      FROM   B
                      WHERE  B.FKID = A.ID) THEN 'yes'
         ELSE 'no'
       END AS hasB
FROM   A  

答案 1 :(得分:2)

SELECT DISTINCT
    a.ID,
    CASE WHEN b.FKID IS NULL THEN 'no' ELSE 'yes' END AS hasB
FROM
    tableA a LEFT JOIN
    tableB b ON a.ID = b.FKID

答案 2 :(得分:1)

根据数据库平台的实际情况,这样的事情应该适合你。你可能需要在像MS Access这样可爱的东西上换一个IIF的情况。

select A.ID, case when B.FKID IS NULL then 'no' else 'yes' end as hasB from A left join B on A.ID = B.FKID

答案 3 :(得分:0)

SELECT ID,“no”as hasB from a where not not(id in(select fkid from b))

联盟

SELECT ID,“yes”as hasB from where where in in(select fkid from b)

答案 4 :(得分:0)

使用以下查询

SELECT DISTINCT ID,IF(FKID,'yes','no') AS hasB
FROM A LEFT JOIN B ON A.ID = B.FKID;

你会得到

+------+------+
| ID   | hasB |
+------+------+
|    1 | no   |
|    2 | no   |
|    3 | yes  |
|    4 | yes  |
+------+------+
4 rows in set (0.07 sec)

答案 5 :(得分:0)

其中任何一项都应该: select distinct a.id,(case when b.fkid is null then 0 else 1 end) as hasb from tablea a left join tableb b on a.id=b.fkid

select a.id,(case when exists(select * from tableb where a.id=fkid) then 1 else 0 end) as hasb from tablea a