SQL Server嵌套select in from子句

时间:2016-02-06 02:00:14

标签: sql sql-server

抱歉,不清楚。我的当前查询如下所示,除了某些条件外,工作正常。

SELECT A.*, 
(SELECT .... from Emp where name = A.Name...... ) 
(SELECT .... from Emp where name = A.Name...... ) 
    ........
FROM (SELECT DISTINCT column1, column2, column3 
FROM xxx 
WHERE condition1) A

有时,下面的查询,即from子句中没有给出结果。

SELECT DISTINCT column1, column2, column3 
FROM xxx 
WHERE condition1

如果上述子查询没有结果,我不希望以下查询因加入而失败

(SELECT .... from Emp where name = A.Name...... ) 
(SELECT .... from Emp where name = A.Name...... )
  1. 当来自from cause的子查询没有返回结果时,显示Emp表中的所有内容而没有连接,即没有名称= A.Name

  2. 当来自from cause的子查询返回结果时,然后在Emp表中显示所有连接,即名称= A.Name

  3. 因此,尝试添加case语句如下,以检查子查询是否给出任何结果。也许有更好的方法来实现这一目标。

    请就此提供帮助。

    SELECT A.*, 
    CASE WHEN exists (select A.*) THEN 
        (SELECT .... from Emp where condition 1...... ) 
    WHEN not exists (SELECT A.*) THEN 
        (SELECT .... from Emp where condition 2...... ) 
    END Column_Dummy 
    FROM (SELECT DISTINCT column1, column2, column3 
    FROM xxx 
    WHERE condition1) A
    

    根据我在下面尝试给出的建议,我收到错误,因为无效的对象名称' A'

    SELECT A.* 
    CASE WHEN (SELECT COUNT(*) FROM A Where ....) = 0 THEN 'not result'       
    ELSE 'you have something there '
    END
    

1 个答案:

答案 0 :(得分:0)

使用COUNT(*)

的查询
 SELECT A.*
       CASE WHEN (SELECT COUNT(*) FROM Table Where ....) = 0 THEN `not result`
            ELSE `you have something there`
       END