我有以下表格及其插入脚本:
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的两行,即如果没有找到特定uid的@XR记录,则应该转到else循环。你能帮我解决这个问题吗?我不想在这里使用 union ,并希望在 SINGLE 查询中执行相同的操作,仅使用 join 中的条件而不是写外部if和else循环。
答案 0 :(得分: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。
答案 1 :(得分: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)