SQL连接2个表而不重复值

时间:2016-06-03 17:41:13

标签: sql join duplicates repeat

我有2个表与1:n的关系。 我想加入它们而不重复(复制)一个表中的值。

首先,我有一张预算表:

id   name  budget
1    John   1000
2    Kim    3000

第二,我有一张消费表:

id   amount
1    112
1    145
1    211

结果应如下所示:

id  name   budget amount
1   John   1000   112
1   null   null   145
1   null   null   211
2   Kim    3000   null

输出也可能是:(这不重要)

id  name   budget amount
1   null   null   112
1   John   1000   145
1   null   null   211
2   Kim    3000   null

这可以用SQL吗?

这是一个重复值的连接:

create temporary table a (id1 int,name varchar(10),budget int);
insert into a (id1,name,budget) values(1,'Maier',1000),(2,'Mueller',2000);
create temporary table if not exists b (id2 int,betrag int);
insert into b (id2,betrag) values(1,100),(1,133),(1,234);
select * from a left join b
on a.id1=b.id2
;

2 个答案:

答案 0 :(得分:2)

关键字DISTINCT用于消除查询结果中的重复行:

select distinct b.id, b.name, b.budget, s.amount
from budgets b left join spendings s 
on b.id = s.id;

您也可以使用Group By子句,其工作方式与Distinct类似。在这种情况下,

select b.id, b.name, b.budget, s.amount
from budgets b left join spendings s 
on b.id = s.id
group by b.id, b.name, b.budget, s.amount;

答案 1 :(得分:0)

create  table a (id1 int,name varchar(10),budget int)
insert into a (id1,name,budget) values(1,'Maier',1000)
insert into a (id1,name,budget) values(2,'Mueller',2000)

create  table b (id2 int,betrag int)
insert into b (id2,betrag) values(1,100)
insert into b (id2,betrag) values(1,133)
insert into b (id2,betrag) values(1,234)
insert into b (id2,betrag) values(2,300)
insert into b (id2,betrag) values(2,400)

select a.id1, CASE WHEN c.themin IS NOT NULL THEN a.name ELSE NULL END AS [name],
CASE WHEN c.themin IS NOT NULL THEN a.budget ELSE NULL END AS [budget],
b.*
from a 
LEFT join b on a.id1=b.id2
LEFT OUTER JOIN (SELECT MIN(betrag) AS [themin], id2 FROM b GROUP BY id2) c ON a.id1 = c.id2 AND b.betrag = c.themin