检查3个不同表中的相同ID

时间:2017-03-02 18:46:39

标签: sql sql-server tsql sql-server-2012

大家好我有以下查询来检查表中是否存在ID:

SELECT CASE WHEN EXISTS (SELECT 1 FROM (SELECT TOP 1 RequestID FROM tT 
     UNION 
     SELECT TOP 1 RequestID FROM tET
     UNION 
     SELECT TOP 1 RequestID FROM tE) AS idSearcher 
WHERE 
     idSearcher.RequestID = 120) THEN 'y' ELSE 'n' END AS alreadyHasID

这样可行,但似乎没有看到 3个表中的任何一个具有相同的ID。以上查询似乎只检查所有3个表是否具有该值。

以上查询的输出为例:

|alreadyHasID |
+-------------+
 n

当它应该为'y'时,在3个表中, 1表有120个

分别运行3个表中的每个表,将其作为输出:

+----------+
|tT        |
+----------+
 no records

+----------+
|tET       |
+----------+
 no records

+----------+
|tE        |
+----------+
 120

如果在 3个表中的任意一个中找到ID,如何修改“y”

3 个答案:

答案 0 :(得分:4)

使用内部联接来过滤ALL匹配的位置:

SELECT CASE WHEN EXISTS(
   SELECT * 
   FROM (tT INNER JOIN tET ON tT.RequestID = tET.RequestID)
      INNER JOIN tE ON tT.RequestID = tE.RequestID
   WHERE tT.RequestID = 120
) THEN 'y' ELSE 'n' END AS alreadyHasID

对于任何你这样做:

SELECT CASE WHEN EXISTS(SELECT * FROM tT WHERE [RequestID] = 120) THEN 'y' 
    WHEN EXISTS(SELECT * FROM tET WHERE RequestID = 120) THEN 'y' 
    WHEN EXISTS(SELECT * FROM tE WHERE RequestID = 120) THEN 'y' ELSE 'n' END as [alreadyHasID]

答案 1 :(得分:2)

select case 
     when exists (select 1 from tT  where RequestID = 120)
       or exists (select 1 from tTE where RequestID = 120)
       or exists (select 1 from tE  where RequestID = 120)
      then 'y'
     else 'n'
     end

答案 2 :(得分:-1)

这太乱了 TOP是非确定性的 您正在检查idSearcher.RequestID = 120

{{1}}