[英]SQL Server - Get data from two tables and within a table
請參閱下面的表格和數據 -
DECLARE @test1 TABLE (Ref nvarchar(10) NULL, Dates datetime NULL);
INSERT INTO @test1(Ref, Dates)
VALUES
('R1', '2018-10-26'),
('R2', '2018-10-26'),
('R5', null);
DECLARE @test2 TABLE (P_Ref nvarchar(50) null, Name nvarchar(50) null);
INSERT INTO @test2(P_Ref, Name)
VALUES
('R1', 'N1'),
('R1', 'N2'),
('R2', 'N1'),
('R2', 'N2'),
('R3', 'N1'),
('R3', 'N2'),
('R4', 'N2'),
('R5', 'N3'),
('R6', 'N3'),
('R7', 'N4');
我正在使用表1 @test1
where
條件,它的Ref
列連接表2 @test2
P_Ref
列。 我想要來自兩個表的所有相關數據以及@test2
表中的所有匹配Name
我的疑問是 -
select t1.Ref, t2.P_Ref, t2.Name from
@test1 t1
right join @test2 t2
on t1.Ref = t2.P_Ref
where t1.Dates is not null
我得到的輸出 -
Ref P_Ref Name
R1 R1 N1
R1 R1 N2
R2 R2 N1
R2 R2 N2
我正在尋找下面的輸出 -
Ref P_Ref Name
R1 R1 N1
R1 R1 N2
R2 R2 N1
R2 R2 N2
NULL R3 N1
NULL R3 N2
NULL R4 N2
有人可以幫助我如何實現這一目標。
提前致謝
請嘗試以下查詢
SELECT t1.Ref, t2.P_Ref, t2.Name
FROM @test1 t1
RIGHT JOIN @test2 t2 ON t1.Ref = t2.P_Ref
WHERE t2.Name IN(
SELECT DISTINCT t2.Name
FROM @test1 t1
JOIN @test2 t2 ON t1.Ref = t2.P_Ref
WHERE t1.Dates IS NOT NULL
)
請嘗試以下查詢
select t1.Ref, t2.P_Ref, t2.Name from
@test1 t1 right join @test2 t2
on t1.Ref = t2.P_Ref
where Name in ('N1', 'N2')
如果預期有大量記錄的Dates
可能不是NULL
那么優化選項將如下所示。
IF OBJECT_ID('tempdb..#ValidRecords') IS NOT NULL
DROP TABLE #ValidRecords
SELECT DISTINCT t2.[Name]
INTO #ValidRecords
FROM @test1 t1
JOIN @test2 t2 ON t1.Ref = t2.P_Ref
WHERE t1.Dates IS NOT NULL
SELECT Ref,
t2.P_Ref,
t2.[Name]
FROM @test1 t1
RIGHT JOIN @test2 t2 ON t1.Ref = t2.P_Ref
INNER JOIN #ValidRecords vr ON vr.[Name] = t2.[Name]
問題是您的WHERE子句將外部聯接轉換為隱式內部聯接。 要過濾外部表,通常最簡單的方法是將外部表的過濾條件移動到連接條件。
select t1.Ref, t2.P_Ref, t2.Name from
@test1 t1
right join @test2 t2
on t1.Ref = t2.P_Ref
and t1.Dates is not null
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.