为 SQL Server 编写,但实际查询应该适用于其他数据库。
设置数据:
declare @Fruit table (FruitID int not null,Fruit varchar(10) not null,UnitPrice int not null)
insert into @Fruit(FruitID,Fruit,UnitPrice) values
(1,'Orange',3),
(2,'Apple',2),
(3,'Grape',4)
declare @FruitDetails table (FruitID int not null,Picture varchar(20) not null,Color varchar(10) not null)
insert into @FruitDetails (FruitID,Picture,Color) values
(1,'Orange_o.jpg','Orange'),
(3,'Grape_p.jpg','Purple'),
(3,'Grape_g.jpg','Green'),
(2,'Apple_g.jpg','Green'),
(2,'Apple_r.jpg','Red')
询问:
select
f.Fruit,
f.UnitPrice,
fd.Picture,
fd.Color
from
@Fruit f
inner join
@FruitDetails fd
on
f.FruitID = fd.FruitID
left join
@FruitDetails fd_anti
on
f.FruitID = fd_anti.FruitID and
fd_anti.Picture < fd.Picture --This is the condition for picking a better row
where
fd_anti.FruitID is null --This eliminates rows where a better row was picked
结果:
Fruit UnitPrice Picture Color
---------- ----------- -------------------- ----------
Orange 3 Orange_o.jpg Orange
Grape 4 Grape_g.jpg Green
Apple 2 Apple_g.jpg Green
这与您的预期结果不符,但是您没有为我们从FruitDetail.