SQL返回不存在的行的信息

时间:2013-02-25 12:23:27

标签: sql sql-server-2008

我在SQLPlus上遇到了这个问题:

从这段代码:

select distinct username, name, surname
from users
where username in ('user1', 'user2');

我明白了:

username         name           surname   
--------------- -------------- -------------
user1            Alex            Ander

但我需要:

username         name           surname   
--------------- -------------- -------------
user1            Alex            Ander
user2            not exists     not exists

或类似的东西。如果用户不存在,则表必须写入用户名,其余内容如“不存在”,

请帮助,

谢谢,

4 个答案:

答案 0 :(得分:1)

这也应该有用;

select distinct T.username, 
                coalesce(u.name, 'not exists'), 
                coalesce(u.surname, 'not exists')
from  (values ('user1'),('user2'),('user3')) as T(username)
      left join Users u on T.username = u.username

答案 1 :(得分:0)

select  distinct username
,       coalesce(name, 'not exists')
,       coalesce(surname, 'not exists')
from    (
        select 'user1' as username
        union all
        select 'user2'
        ) list
left join
        users
on      list.username = users.username

答案 2 :(得分:0)

SELECT DISTINCT username,
ISNULL(Name,'Not Exists'),
ISNULL(Surname,'Not Exists')
FROM users
  WHERE (username IN ('user1','user2') OR username IS NULL)

答案 3 :(得分:0)

希望现在更清楚地解释一下:

我现在拥有的原始代码是:

select distinct username, name, surname
from users u, accounts a
where u.user_nr = a.user_nr
and username in (
'existing_user',
'not_existing_user'
) order by username;

它给了我:

USERNAME                  NAME            SURNAME  
------------------------- --------------- ---------------
existing_user              Hello           All

1 row selected.

我需要:

USERNAME                  NAME            SURNAME  
------------------------- --------------- ---------------
existing_user             Hello           All
not_existing_user     Not Exists      Not Exists

2 row selected.

问题:用户not_existing_user不存在于DataBase中, 但是查询必须从代码中向他显示 使用信息 - 用户不在数据库中。 对于500个用户,我无法单独检查每个人:/