sql - 在 INNER JOIN 中选择 TOP

标签 sql sql-server sql-server-2008 tsql sql-server-2008-r2

我在 SQL Server 中创建了这个简单的数据库:

create database product_test
go

use product_test
go

create table product 
(
    id int identity primary key,
    label varchar(255),
    description text,
    price money, 
);

create table picture 
(
    id int identity primary key, 
    p_path text, 
    product int foreign key references product(id) 
); 

insert into product 
values ('flip phone 100', 'back 2 the future stuff.', 950),
       ('flip phone 200', 's;g material', 1400)

insert into picture 
values ('1.jpg', 1), ('2.jpg', 1), ('3.jpg', 2)

我想要的是为每个产品选择所有 产品和只有一张 图片。任何帮助是极大的赞赏。

最佳答案

为此目的,我是outer apply的粉丝:

select p.*, pi.id, pi.path
from product p outer apply
     (select top 1 pi.*
      from picture pi
      where pi.product = p.id
     ) pi;

您可以包含一个 order by 来获取一张特定的图片(例如,具有最低或最高 ID 的图片)。或者,order by newid() 得到一个随机的。

关于sql - 在 INNER JOIN 中选择 TOP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42444359/

相关文章:

mysql - 每天SQL峰值

C# - 如何显示有关从另一个表检索的 SQL 表的元数据?

sql - T-SQL 计算不同年份范围之间的持续时间(以月为单位)

mysql - 如何在一个 View 中从 SQL 中的另一个表求和?

mysql - MySQl 与 SQL Server 与 Oracle 中的分层查询

sql - 索引 View 和左连接一劳永逸

sql - 如何从 SQL Server 中删除图表支持对象?

sql - 统计/汇总查询:完全扫描还是索引或分区?

sql-server - 如何列出(或导出)数据库中所有触发器的代码?

sql-server - 在单个查询 MS SQL 中更新多条记录