另一个表上的同一个表的两列上的内连接,包括OR条件

时间:2012-12-21 17:39:30

标签: sql sql-server

表1 - USERS

user_id | email_id         | type
---------------------------------------
000121  | test_20@test.com | EXT
000125  | best_21@test.com | LOT
000128  | lite_21@test.com | EXT

表2- HISTORY

old_user_id | new_user_id | another_type
----------------------------------------
000128      | 000121      | INIT  

我手边有email_id test_20@test.com,我想做一个应该返回1的连接查询,如果我有user_email_id,则在USERS表中EXT为TYPE,HISTORYANOTHER_TYPEINIT;

我有old_user_id的单个联接查询。

IF EXISTS (SELECT 1 FROM   history cmr (nolock) 
                  INNER JOIN users au (nolock) 
                          ON au.user_id = cmr.old_user_id 
                  AND cmr.another_type = 'INIT  'AND au.type = 'EXT' 
                   AND au.email_id = 'test_20@test.com') 
  SELECT 1 ELSE   SELECT 0 

当我查询test_20@test.comtest_20@test.com时,它应返回1.我还要为new_user_id添加加入条件。

因此EXT中的用户(旧的或新的)应为USERS,而INIT

中的HISTORY应为{{1}}

提前致谢

3 个答案:

答案 0 :(得分:4)

IF EXISTS 
(
SELECT * FROM   history cmr 
Left JOIN users au  ON au.user_id = cmr.old_user_id  AND cmr.another_type = 'INIT  'AND au.type = 'EXT'  AND au.email_id = 'test_20@test.com' 
Left JOIN users au2  ON au2.user_id = cmr.new_user_id  AND cmr.another_type = 'INIT  'AND au2.type = 'EXT'  AND au2.email_id = 'test_20@test.com'
Where (au.user_id is NOT NULL) or (au2.user_id is NOT NULL)
)
SELECT 1 ELSE   SELECT 0 

答案 1 :(得分:2)

使用case when BTW user是保留关键字。所以你可能想用方括号 它

查询1:

SELECT case when 
       EXISTS (Select * From historyT cmr 
       Left Join userT au  
       On (au.user_id = cmr.old_user_id  
       And cmr.another_type = 'INIT'
       And au.type = 'EXT'  
       And au.email_id = 'test_20@test.com')) 
       Then 1
       Else 0
End  Status               
;

QUERY2:

SELECT case when 
   EXISTS (Select * From historyT cmr 
   Left Join userT au  
   On (au.user_id = cmr.old_user_id  
   And cmr.another_type = 'INIT'
   And au.type = 'EXT'  
   And au.email_id = 'test_20@test.com') 
   Left Join userT au2  
   On (au2.user_id = cmr.new_user_id  
   And cmr.another_type = 'INIT' 
   And au2.type = 'EXT'  
   And au2.email_id = 'test_20@test.com'
   And (au.user_id is Not Null) 
   or (au2.user_id is Not Null)))
   Then 1
   Else 0

结束状态 ;

结果:

STATUS
1

答案 2 :(得分:2)

试试这个:

IF EXISTS (SELECT 1 
           FROM 
                history cmr (nolock) INNER JOIN 
                users au (nolock) 
           ON 
                (au.user_id = cmr.old_user_id or au.user_id = cmr.new_user_id)
           WHERE 
                  cmr.another_type = 'INIT' AND 
                  au.type = 'EXT' AND 
                  au.email_id = 'test_20@test.com') 
  SELECT 1 
ELSE   
  SELECT 0