如何在IF EXISTS子查询中使用SQL Select语句?


76

如何使用IF EXISTS语句从子查询中选择布尔值(SQL Server)?

应该是这样的:

SELECT 
  TABEL1.Id, 
  NewFiled = (IF EXISTS(SELECT Id FROM TABLE2 WHERE TABLE2.ID = TABEL1.ID) 
                 SELECT 'TRUE' 
              ELSE 
                 SELECT 'FALSE') 
FROM TABEL1

Answers:


128

用途CASE

SELECT 
  TABEL1.Id, 
  CASE WHEN EXISTS (SELECT Id FROM TABLE2 WHERE TABLE2.ID = TABLE1.ID)
       THEN 'TRUE' 
       ELSE 'FALSE'
  END AS NewFiled  
FROM TABLE1

如果TABLE2.ID是唯一键或主键,则也可以使用以下命令:

SELECT 
  TABEL1.Id, 
  CASE WHEN TABLE2.ID IS NOT NULL
       THEN 'TRUE' 
       ELSE 'FALSE'
  END AS NewFiled  
FROM TABLE1
  LEFT JOIN Table2
    ON TABLE2.ID = TABLE1.ID

18

您还可以使用ISNULL和select语句获取此结果

SELECT
Table1.ID,
ISNULL((SELECT 'TRUE' FROM TABLE2 WHERE TABLE2.ID = TABEL1.ID),'FALSE') AS columName,
etc
FROM TABLE1

2
我只是注意到您说您想要布尔值,选择1/0可能比选择True / False更好
Purplegoldfish 2011年

8
SELECT Id, 'TRUE' AS NewFiled FROM TABEL1
INTERSECT
SELECT Id, 'TRUE' AS NewFiled FROM TABEL2
UNION
SELECT Id, 'FALSE' AS NewFiled FROM TABEL1
EXCEPT
SELECT Id, 'FALSE' AS NewFiled FROM TABEL2;

4
+1用于合并INTERSECTUNIONEXCEPT在一个查询中!
ypercubeᵀᴹ

对于同一件事,减号1 –以不必要的复杂性炫耀,这将使阅读和维护变得更加困难。
Anon_unique

@Anon_unique大声笑对我来说这段代码非常简单,也许是因为我认为基于集合。
某天

4

使用一条CASE语句,并按照以下步骤操作:

SELECT 
    T1.Id [Id]
    ,CASE WHEN T2.Id IS NOT NULL THEN 'TRUE' ELSE 'FALSE' END [Has Foreign Key in T2]
FROM
    TABLE1 [T1]
    LEFT OUTER JOIN
        TABLE2 [T2]
        ON
        T2.Id = T1.Id
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.