简体   繁体   English

sql server顶级查询

[英]sql server top query

I don't know what's wrong with this query : 我不知道这个查询有什么问题:

select * from products , top 1 * from pic 
where products.productId = pic.productId

I have Products and Pic tables , every products could have 1 to n pic and I would like to return every product and the first pic of that 我有产品和Pic表,每个产品可以有1到n pic,我想返回每个产品和第一张照片

The picture of diagram may help 图表的图片可能有所帮助 在此输入图像描述

You need to have a way of uniquely identifying each pic, so I'm asuming that table as an ID column... 你需要有一种唯一识别每张图片的方法,所以我把那张桌子作为ID列...

SELECT
  *
FROM
  products
LEFT JOIN
  pic
    ON pic.Id = (SELECT TOP 1 id FROM pic WHERE productID = products.ProductID ORDER BY id DESC)


EDIT 编辑

Inspired by another answer, using APPLY instead... 灵感来自另一个答案,使用APPLY代替......

SELECT
  *
FROM
  products
OUTER APPLY
  (SELECT TOP 1 * FROM pic WHERE productID = products.ProductID ORDER BY id DESC) AS pic

You need a subquery to 你需要一个子查询

  • select the first PicID's for each ProductID 为每个ProductID选择第一个PicID
  • join with Pic table itself to get the additional columns 与Pic表本身连接以获取其他列
  • join with Products to get the product columns 加入产品以获取产品列

SQL Statement SQL语句

SELECT  *
FROM    Products prod
        LEFT OUTER JOIN Pic p ON p.ProductID = prod.ProductID
        LEFT OUTER JOIN (
          SELECT PicID = MIN(PicID)
                 , ProductID
          FROM   Pic
          GROUP BY
                 ProductID
        ) pm ON pm.PicID = p.PicID

There is also way with subsection but please avoid sub select as much as You can in yours TSQL 还有分段的方法但请避免在您的TSQL中尽可能多地进行子选择

Select 
*
,(select top(1) adress from pic where pic.productid=products.id /* if u wanna you also can order by id */   ) as Id
from products 

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

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