简体   繁体   English

在INNER JOIN中选择TOP

[英]SELECT TOP inside INNER JOIN

I created this simple database in SQL Server: 我在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)

What I want is to select all products and only one picture for each product. 我想要的是选择所有产品,每种产品选择一张图片。 Any help is greatly appreciated. 任何帮助是极大的赞赏。

I'm a fan of outer apply for this purpose: 我是outer apply的粉丝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;

You can include an order by to get one particular picture (say, the one with the lowest or highest id). 您可以通过包含order by来获取一张特定图片(例如,ID最低或最高的图片)。 Or, order by newid() to get a random one. 或者, order by newid()命令获取随机的。

I would use a windowing function like this: 我会使用这样的窗口函数:

SELECT *
FROM product 
JOIN (
  SELECT id, product, p_path, 
         row_number() OVER (PARTITION BY product ORDER BY id ASC) as RN
  FROM picture
) pic ON product.id = pic.product AND pic.RN = 1

As you can see here I am selecting the picture with the lowest id ( ORDER BY id ASC ) -- you can change this order by to your requirements. 正如您在这里看到的那样,我选择ID最低的图片( ORDER BY id ASC ) - 您可以根据您的要求更改此订单。

SELECT 
*,
(
    SELECT TOP 1 p2.p_path
    FROM dbo.picture p2
    WHERE p.id = p2.product
) AS picture
FROM dbo.product p

Or with join: 或者加入:

SELECT 
*
FROM dbo.product p
INNER JOIN 
(
    SELECT p2.product, MIN(p2.p_path) AS p_path
    FROM dbo.picture p2
    GROUP BY p2.product
) AS pt
ON p.id = pt.product

But you need to change p_path to varchar type 但是您需要将p_path更改为varchar类型

Have you tried using a correlated sub-query? 您是否尝试过使用相关的子查询?

SELECT *, (SELECT TOP 1 p_path FROM picture WHERE product = p.id ORDER BY id) 
FROM picture p

Hope this helps, 希望这可以帮助,

just group by and take min or max 只需分组并采取最小或最大
left join in case there is no picture 如果没有图片,请左连接

select pr.ID, pr.label, pr.text, pr.price
     , min(pic.p_path)
from product pr 
left join picture pic 
on pic.product = pr.ID 
group by pr.ID, pr.label, pr.text, pr.price 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM