[英]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.