如果IN子查询没有行,如何返回所有行?

时间:2017-01-18 20:16:42

标签: sql sql-server tsql

以下是示例查询

hidden

我需要选择IN子句中的所有用户,但是如果子查询没有返回记录,我需要选择所有用户(即忽略IN子句)

2 个答案:

答案 0 :(得分:6)

Select *
  from tb.Users u
 where u.Approved = 1
   and (
    u.userID IN ( SELECT us.UserID us
                        FROM tb.UserStatementes us
                       WHERE us.LogDate between date1 and date2 
                       )
    or not exists (
        select 1
          from tb.UserStatementes us
          where us.LogDate between date1 and date2
        )
      )

答案 1 :(得分:1)

Select *
  from tb.Users u
 where u.Approved = 1
   and ( exists        ( SELECT 1 
                           FROM tb.UserStatementes us
                           WHERE us.LogDate between date1 and date2 
                             AND us.USERID = u.USERID )
         or not exists ( SELECT 1 
                           FROM tb.UserStatementes us
                          WHERE us.LogDate between date1 and date2 )
       )