2011-09-16 73 views
0

我有自己的插入腳本如下表:如何使有條件的SQL加入

DECLARE @A TABLE 
    (
     [ID] INT IDENTITY, 
     [SID] INT 
    ) 


DECLARE @EP TABLE 
    (
     [SID] INT , 
     [RID] INT , 
     [HR] INT 
    ) 

DECLARE @XR TABLE 
    (
     [SID] INT , 
     [RID] INT , 
     [UID] INT 
    ) 

DECLARE @SR TABLE 
    (
     [RID] INT , 
     [RNAME] VARCHAR(10), 
     [SID] INT 
    ) 


INSERT INTO @A 
SELECT 1 UNION 
SELECT 2 


INSERT INTO @EP 
SELECT 1, 1, 1 UNION 
SELECT 1, 2, 1 UNION 
SELECT 1, 3, 1 UNION 
SELECT 2, 4, 1 UNION 
SELECT 2, 5, 1 UNION 
SELECT 2, 6, 1 

INSERT INTO @XR 
SELECT 1, 1, 1 UNION 
SELECT 1, 2, 1 UNION 
SELECT 1, 2, 2 UNION 
SELECT 2, 4, 1 UNION 
SELECT 2, 5, 2 

INSERT INTO @SR 
SELECT 1,'Apple', 1 UNION 
SELECT 2,'Mango', 1 UNION 
SELECT 3,'Banana',1 UNION 
SELECT 4,'Apple', 2 UNION 
SELECT 5,'Mango', 2 UNION 
SELECT 6,'Banana',2 

當我運行下面的SQL查詢,我得到兩個輸出行這是很好的:

DECLARE @UD INT 
SET @UD=1 

SELECT * FROM @A A 
WHERE EXISTS(
    SELECT 1      
    FROM @EP [EP]      
    INNER JOIN @XR XR ON [EP].SID = A.SID 
    WHERE [EP].SID = A.SID      
    AND [EP].RID = XR.RID 
    AND [EP].[HR] = 1      
    AND XR.UID = @UD 
) 
--OUTPUT 
--ID   SID 
------------- ----------- 
--1   1 
--2   2 

但是當我用「@ UD = 3」運行上面的查詢時,我沒有記錄。我想提出一個條件在這裏加入的應該是這樣的:

SELECT * FROM @A A 
--IF((SELECT COUNT(*) FROM @XR XR WHERE XR.XR=A.SID)>0) 
WHERE EXISTS(
    SELECT 1      
    FROM @EP [EP]      
    INNER JOIN @XR XR ON [EP].SID = A.SID 
    WHERE [EP].SID = A.SID      
    AND [EP].RID = XR.RID 
    AND [EP].[HR] = 1      
    AND XR.UID = @UD 
) 
--ELSE 
WHERE EXISTS(
    SELECT 1      
    FROM @EP [EP]      
    INNER JOIN @SR SR ON SR.SID = A.SID 
    WHERE [EP].SID = A.SID      
    AND [EP].RID = SR.RID 
    AND [EP].[HR] = 1      
    AND SR.[RNAME] = 'Banana' 
) 

的abover查詢應返回兩行兩@UID 1和3,即如果沒有找到記錄@XR它應該特別UID去其他循環。你能幫我解決這個問題嗎?我不想去工會這裏,並希望在同樣做SINGLE查詢條件只加入而不寫入外部if和其他循環。

+0

[Rü尋找一個外部聯接? –

回答

1
SELECT * FROM @A A 
WHERE ((SELECT COUNT(*) FROM @XR XR WHERE XR.XR=A.SID)=0 AND EXISTS(
    SELECT 1      
    FROM @EP [EP]      
    INNER JOIN @XR XR ON [EP].SID = A.SID 
    WHERE [EP].SID = A.SID      
    AND [EP].RID = XR.RID 
    AND [EP].[HR] = 1      
    AND XR.UID = @UD 
)) OR ((SELECT COUNT(*) FROM @XR XR WHERE XR.XR=A.SID)!=0 AND EXISTS(
    SELECT 1      
    FROM @EP [EP]      
    INNER JOIN @SR SR ON SR.SID = A.SID 
    WHERE [EP].SID = A.SID      
    AND [EP].RID = SR.RID 
    AND [EP].[HR] = 1      
    AND SR.[RNAME] = 'Banana' 
)) 

即只是用一個簡單的布爾結合兩者。您可能不需要第二個COUNT(*)查詢BTW。

0

這應該這樣做,如果我理解正確的要求:

SELECT DISTINCT 
    A.* 
FROM @A AS A 
JOIN @EP AS EP ON A.SID = EP.SID 
LEFT JOIN @XR AS XR ON EP.RID = XR.RID 
LEFT JOIN @SR AS SR ON SR.SID = A.SID 
WHERE EP.HR = 1 
    AND (XR.UID = @UD OR RNAME IS NOT NULL)