2016-09-15 86 views
-1

让的说我想创造这样的事情SQL SELECT语句中的情况下

select t.*, 
     (case when (select name from table2 where idtable2 = t.idtable1)= NULL then '0' 
     end) as result 
from table1 t 

我该怎么办呢? 谢谢

对不起我的错误,是这句话它works..but它不工作,如果有这样的情形语句之前的子查询..

选择T *(请从表3,其中idtable3名= t.idtable3)作为nametable3, (情况下(请从表2,其中idtable2 = t.idtable1名)= NULL,则 '0' 结束)作为结果 从表1牛逼

+0

这应该工作,但可能需要一个'LIMIT 1';但通常(并不总是)加快两个表的连接并直接使用该值。 – Uueerdo

+1

你应该解释你想要的逻辑。 –

+1

正在返回表中每一行的查询的SELECT列表中的相关子查询。如果table1包含一百万行,则该子查询将被执行一百万次。 *不寒而栗*。 (当我说......“一个meeelyon行”时,我很想将我的小指放在我嘴角,邪恶博士的风格。) – spencer7593

回答

3

我想你想要exists

select t.*, 
     (case when not exists (select 1 
           from table2 t2 
           where t2.idtable2 = t.idtable1 
          ) 
      then '0' 
     end) as result 
from table1 t; 

或者,您的查询将与is null工作:

select t.*, 
     (case when (select t2.name 
        from table2 t2 
        where t2.idtable2 = t.idtable1 
       ) is null 
      then '0' 
     end) as result 
from table1 t; 

这假设子查询返回一行。

0

假设table2的idtable2值始终是唯一的,您可以对table2执行左连接,而不是子查询。

CREATE TABLE #table1 
(
    idtable1 INT 
    ,someValue varchar(25) 
) 

CREATE TABLE #table2 
(
    idtable2 INT 
    ,name varchar(25) 
) 


INSERT INTO #table1 values(1,'a'),(2,'b'),(3,'c'),(4,'d') 
INSERT INTO #table2 values(1,'Bob'),(2,'Kim'),(3,'Fred'),(5,'Sally') 

SELECT t.* 
    ,CASE 
     WHEN t2.NAME IS NULL 
      THEN '0' 
     END AS Result 
FROM #table1 t 
LEFT JOIN #table2 t2 
    ON t.idtable1 = t2.idtable2