使用内部联接,每次比赛左侧仅返回1条记录

时间:2019-06-04 22:33:41

标签: sql join

我不知道为什么我无法弄清楚这个ATM。 Here's a very contrived example

create table Dog (
  [Name] varchar(10), 
  [BreedId] int
);

create table Breed (
  [BreedId] int,
  [Name] varchar(10)
);

insert into DOG (name, breedid)
VALUES ('Mix', 1),
  ('Mix2', 2),
  ('Mix2', 3);

insert into breed(breedid, name)
VALUES 
  (1, 'BullDog'),
  (1, 'Poodle'),
  (2, 'BullDog'),
  (2, 'Poodle'),
  (4, 'Poodle');

以下内容会产生两行,因为联接表具有两个匹配的值,只要右边有匹配的记录,我只想要一个值

select d.*
from dog d
inner join breed b on d.breedid = b.breedid 

导致:

  

混合1

     

混合1

     

混合2

     

混合2

是否可以在联接子句中 / 执行此操作,而无需在where格或分组依据等其他选项中执行select

select d.*
from dog d
where d.breedid in (select breedid from breed)

2 个答案:

答案 0 :(得分:1)

尝试“选择不同”。您还可以按重复的列进行分组,并采用具有唯一值的列的max()。

编辑:如何在不使用where子句的情况下按品种。品种进行过滤。

select d.*
From dog as d
Inner join (select distinct breedid from breed) as b on b.breedid = d.breedid

答案 1 :(得分:0)

如果您只想要exists中的列,我将使用dog

select d.*
from dog d
where exists (select 1 from breed b where d.breedid = b.breedid);