如果在SQL中找不到某些值,则显示NULL

时间:2016-10-06 13:12:25

标签: sql sql-server null

我这里有一个示例数据

id  name
----------
1   Test1
2   Test2
3   Test3
4   Test4

所以当我执行此QUERY

select id,name from table1 where name IN ('Test1','Test3','Test5')

它给我输出

id  name
----------
1   Test1
3   Test3

我有什么方法可以像这样输出

id     name
----------
1      Test1
3      Test3
null   Test5

4 个答案:

答案 0 :(得分:4)

您可以使用table value constructors(> = 2008):

SELECT CASE WHEN EXISTS(SELECT 1
                     FROM   table1 t
                     WHERE  E.Name = t.Name) 
           THEN E.Id
           ELSE NULL END AS Id,
       Name
FROM   (VALUES(1,'Test1'),(3,'Test3'),(5,'Test5')) E(Id,Name)  

答案 1 :(得分:2)

它不漂亮,但CTE会这样做

with MyData as
(
    select 'Test1' as MyName
    union
    select 'Test3' as MyName
    union
    select 'Test5' as MyName
)
select MyData.MyName, T1.id
from MyData
left join Table1 T1
on T1.Name = MyData.MyName

答案 2 :(得分:1)

确实使用带有外连接的Values表构造函数:

Select o.id, m.name
   from (VALUES ('Test1'), ('Test3'), ('Test5')) t(name)
      left join myData o 
         on o.name = t.name

答案 3 :(得分:0)

刚刚加入一个表格' Test1',' Test3',' Test5'到有问题的表

select id,t.name
from
(
    select 'Test1' as Name
    union
    select 'Test3' as Name
    union
    select 'Test5' as Name
) t
left join table1 on t.Name = table1.Name;

这将枚举所有匹配的id或返回null作为id。您可能希望仅返回3行

select max(id) -- min(id)
    , t.name 
from
(
    select 'Test1' as Name
    union
    select 'Test3' as Name
    union
    select 'Test5' as Name
) t
left join table1 on t.Name = table1.Name
group by t.name;