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

问题描述 投票:0回答: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
    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

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

sql-server sql-server-2008
2个回答
0
投票

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

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

0
投票

您现有的查询包含两个联合的行,只输出它,并且您不需要“公共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
© www.soinside.com 2019 - 2024. All rights reserved.