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

如何选择布尔值从子查询与 IFEXISTS 语句(SQLServer) ?

应该是这样的:

SELECT
TABLE1.Id,
NewFiled = (IF EXISTS(SELECT Id FROM TABLE2 WHERE TABLE2.ID = TABLE1.ID)
SELECT 'TRUE'
ELSE
SELECT 'FALSE')
FROM TABLE1
256029 次浏览

You can also use ISNULL and a select statement to get this result

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

Use CASE:

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

If TABLE2.ID is Unique or a Primary Key, you could also use this:

SELECT
TABLE1.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

Use a CASE statement and do it like this:

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
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;

You can use EXISTS to check if a column value exists in a different table.

SELECT
TABLE1.id,
EXISTS (SELECT 1 FROM TABLE2 WHERE TABLE2.id = TABLE1.id) AS columnName
FROM TABLE1

Example:

CREATE TABLE TABLE1 (
id INTEGER PRIMARY KEY,
some_column TEXT NOT NULL
);
CREATE TABLE TABLE2 (
id INTEGER PRIMARY KEY,
some_column TEXT NOT NULL
);


INSERT INTO TABLE1 VALUES
(111, 'lorem ipsum'),
(222, 'and'),
(333, 'some'),
(444, 'random'),
(123, 'strings');
 

INSERT INTO TABLE2 VALUES
(111, 'lorem ipsum'),
(444, 'random'),
(123, 'strings');


SELECT
TABLE1.id,
EXISTS (SELECT 1 FROM TABLE2 WHERE TABLE2.id = TABLE1.id) AS columnName
FROM TABLE1

Output:

id someColumn
111 1
123 1
222 0
333 0
444 1