简体   繁体   English

SQL Server - 从两个表和表中获取数据

[英]SQL Server - Get data from two tables and within a table

Please see my table and data below - 请参阅下面的表格和数据 -

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');

I am using where condition in table 1 @test1 , it's Ref column join with table 2 @test2 P_Ref column. 我正在使用表1 @test1 where条件,它的Ref列连接表2 @test2 P_Ref列。 I want all the related data from both tables as well as all the matches Name from @test2 table 我想要来自两个表的所有相关数据以及@test2表中的所有匹配Name

My query is - 我的疑问是 -

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

The output I am getting - 我得到的输出 -

   Ref    P_Ref    Name
    R1      R1      N1
    R1      R1      N2
    R2      R2      N1
    R2      R2      N2

I am looking below output - 我正在寻找下面的输出 -

   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

Could someone please help me how to achieve this. 有人可以帮助我如何实现这一目标。

Thanks in advance 提前致谢

Try the following query 请尝试以下查询

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
  )

Try the below query 请尝试以下查询

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')

If there are large number of records expected whose Dates may not be NULL then an optimized option will be as below. 如果预期有大量记录的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]

The problem is that your WHERE clause is turning your outer join into an implicit inner join. 问题是您的WHERE子句将外部联接转换为隐式内部联接。 To filter the outer table, it's usually easiest to move the filter condition for the outer table to the join condition. 要过滤外部表,通常最简单的方法是将外部表的过滤条件移动到连接条件。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM