sql select语句里面的情况

时间:2016-09-15 22:44:44

标签: mysql sql case-statement

让我说我想创造这样的东西

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

我该怎么办? 谢谢

对不起我的错误,是的,它的说法是有效的..但如果在案例陈述之前有子查询,它就不起作用。

选择t。*,(从table3中选择idtable3 = t.idtable3的名称)作为nametable3,        (情况何时(从table2中选择idtable2 = t.idtable1的名称)= NULL然后' 0'         结果) 来自table1 t

2 个答案:

答案 0 :(得分: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;

这假设子查询返回一行。

答案 1 :(得分: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
相关问题