如何使用公共列从多个表中检索数据

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用公共列从多个表中检索数据相关的知识,希望对你有一定的参考价值。

我试图通过加入公共列来从两个表中获取数据。但它给了我重复的东西。

 ;WITH LocID AS
    (
    SELECT 1 AS LocID, 1 AS CommonID 
    UNION ALL 
    SELECT 2 AS LocID, 1 AS CommonID 
    ), 

    LocAddress AS(
    SELECT 456 AS AddressID, 'Address-1'AS 'Address',  'City-1' AS City, 'State-1' AS 'State', 1 AS CommonID
    UNION ALL 
    SELECT 789 AS AddressID, 'Address-2'AS 'Address',  'City-2' AS City, 'State-2' AS 'State', 1 AS CommonID
    )

        SELECT L.LocID, A.Address, A.City, A.State FROM LocID L INNER JOIN LocAddress A ON L.CommonID = A.CommonID ;

所需的输出只有两行,如下所示。

LocID地址城市州

1地址-1城市-1国家-1

2地址-2城市-2国家-2

有什么方法可以得到这个吗?

答案

这是预料之中的。结果是正确的。如果您希望输出与上面提到的完全相同,则查询应如下所示:

 ;WITH LocID AS
    (
    SELECT 1 AS LocID, 1 AS CommonID 
    UNION ALL 
    SELECT 2 AS LocID, 2 AS CommonID 
    ), 

    LocAddress AS(
    SELECT 456 AS AddressID, 'Address-1'AS 'Address',  'City-1' AS City, 'State-1' AS 'State', 1 AS CommonID
    UNION ALL 
    SELECT 789 AS AddressID, 'Address-2'AS 'Address',  'City-2' AS City, 'State-2' AS 'State', 2 AS CommonID
    )

        SELECT L.LocID, A.Address, A.City, A.State FROM LocID L INNER JOIN LocAddress A ON L.CommonID = A.CommonID ;

编辑:

或者,您可以考虑加入2个字段,如下所示:

 ;WITH LocID AS
    (
    SELECT 1 AS LocID, 1 AS CommonID 
    UNION ALL 
    SELECT 2 AS LocID, 1 AS CommonID 
    ), 

    LocAddress AS(
    SELECT 456 AS AddressID, 'Address-1'AS 'Address',  'City-1' AS City, 'State-1' AS 'State', 1 AS CommonID, 1 AS LocID
    UNION ALL 
    SELECT 789 AS AddressID, 'Address-2'AS 'Address',  'City-2' AS City, 'State-2' AS 'State', 1 AS CommonID, 2 AS LocID
    )

        SELECT L.LocID, A.Address, A.City, A.State FROM LocID L INNER JOIN LocAddress A ON L.CommonID = A.CommonID AND L.LocID = A.LocID ;
另一答案

您现有的查询包含两个联合的行,只输出它,并且您不需要“公共ID”来执行此操作。

SELECT * 
FROM (
    SELECT 456 AS AddressID, 'Address-1'AS 'Address',  'City-1' AS City, 'State-1' AS 'State'
    UNION ALL 
    SELECT 789 AS AddressID, 'Address-2'AS 'Address',  'City-2' AS City, 'State-2' AS 'State'
    ) AS d

以上是关于如何使用公共列从多个表中检索数据的主要内容,如果未能解决你的问题,请参考以下文章

如何通过主 ID 以外的列从 DynamoDB 检索数据

用单个列从另一个表更新一个表中的多个列?

如何从多个聚合表中检索数据?

使用 LINQ 从多个表中检索数据

使用其他表的列从表中删除

如何使用两列从关系表中删除一行