T-SQL: How to Select Values in Value List that are NOT IN the Table?

前端 未结 6 1979
天命终不由人
天命终不由人 2020-12-07 20:01

I have a list of e-mail addresses, some of them are in my table, some of them are not. I want to select all e-mails from that list and whether they are in the table or not.

6条回答
  •  Happy的楠姐
    2020-12-07 20:53

    When you do not want to have the emails in the list that are in the database you'll can do the following:

    select    u.name
            , u.EMAIL
            , a.emailadres
            , case when a.emailadres is null then 'Not exists'
                   else 'Exists'
              end as 'Existence'
    from      users u
              left join (          select 'email1' as emailadres
                         union all select 'email2'
                         union all select 'email3') a
                on  a.emailadres = u.EMAIL)
    

    this way you'll get a result like

    name | email  | emailadres | existence
    -----|--------|------------|----------
    NULL | NULL   | a@b.com    | Not exists
    Jan  | j@j.nl | j@j.nl     | Exists
    

    Using the IN or EXISTS operators are more heavy then the left join in this case.

    Good luck :)

提交回复
热议问题