2

表 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我有的话,是在USERSEXT中 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.comortest_20@test.com时,它应该返回 1。我想为new_user_id也添加连接条件。

所以任何一个用户(旧的或新的)都应该EXTUSERS,并且应该INITHISTORY

提前致谢

4

3 回答 3

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 
于 2012-12-21T17:46:03.013 回答
2

用途case whenBTWuser是保留关键字。所以你可能想用方括号。

查询一:

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               
;

查询2:

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
于 2012-12-21T17:48:57.903 回答
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 
于 2012-12-21T18:32:53.293 回答