SQL连接唯一键上的两个表的列

问题描述 投票:0回答:4

假设我有两个表,A和B,两个表都有一个唯一的键,如下所示(实际表中当然有更多的行和列):

Unique_Key       A        B
____________________________
    ABC          1        2
    BCD          5        6
    DDD          10       11


 Unique_Key      C        D
____________________________
    ABC          6        7
    BCD          8        9
    DDD          100      200

我想加入Unique_Key上两个表的列,以产生以下输出:

Unique_Key       A        B         C         D
_________________________________________________
    ABC          1        2         6         7
    BCD          5        6         8         9
    DDD          10       11        100       200

我试过这个:

select 
    [A], [C]
from 
    tableA r with (nolock) join tableB l with (nolock) on r.Unique_Key = 
l.Unique_Key

它的工作原理很多,因为它组合了表,但它产生了重复的行,我不知道为什么。这实际上是我想要避免的 - 拥有重复的行。

谢谢!

sql sql-server
4个回答
1
投票

你可以使用在这种情况下运行良好的Join命令。

SELECT A.Unique_Key, A.Atable_Column1, A.Atable_Column2, B.Btable_Column3, B.Btable_Column4 
From Table1 A  inner join Table2 B
 on A.Unique_Key = B.Unique_Key

0
投票

你可以使用group by with aggregation

select 
    r.Unique_Key,max([A]), max([C])
from 
    tableA r join tableB l on r.Unique_Key = 
l.Unique_Key
group by r.Unique_Key

0
投票

如果unique_key在每个表中真的是唯一的,那么这将做你想要的而不产生重复:

select r.unique_key, r.a, r.b, l.c, l.d
from tableA r join
     tableB l 
     on r.Unique_Key = l.Unique_Key;

如果您获得重复项,则您的密钥不是唯一的。您可以通过运行以下方法识别具有重复项的密钥:

select unique_key
from tableA r
group by unique_key
having count(*) > 1;

和:

select unique_key
from tableB l
group by unique_key
having count(*) > 1;

根据您选择的名称,您可能需要修复基础数据。


0
投票

tableA.AtableB.C都不是唯一的,或者我理解这一点。

Unique_Key | A | B
-----------+---+--
AAA        | 1 | 1
BBB        | 1 | 2
CCC        | 2 | 3

Unique_Key | C | D
-----------+---+--
AAA        | 1 | 1
BBB        | 1 | 2
CCC        | 4 | 5

你会得到的

A | C
--+--
1 | 1
1 | 1
2 | 4

你想在哪里

A | C
--+--
1 | 1
2 | 4

使用DISTINCT

select distinct tablea.a, tableb.c
from tablea 
join tableb on tablea.unique_key = tableb.unique_key;
© www.soinside.com 2019 - 2024. All rights reserved.