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

时间:2018-03-01 23:36:08

标签: sql-server sql-server-2008

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

 ;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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 ;