简体   繁体   English

选择与自定义联接表成多对多关系的第一行

[英]Selecting top row in a many to many relationship with custom join table

I have three tables in a MM relationship: 我在MM关系中有三个表:

在此处输入图片说明

I'm having a lot of trouble trying to figure out how I can retrieve all Bundles with only the first related inventory item ordered by Inventory.Stock ASC but also return the Bundles_Inventory.InventoryRequired field. 我在尝试找出如何仅使用Inventory.Stock ASC订购的第一个相关库存项目来检索所有Bundle时遇到很多麻烦,而且还返回Bundles_Inventory.InventoryRequired字段。

I've seen other responses to similar questions but none of them take into account a custom join table. 我已经看到了对类似问题的其他回答,但是没有一个考虑到自定义联接表。

How can I select all Bundles ordered by Inventory.Stock ASC and also include Bundles_Inventory.InventoryRequired for that record? 如何选择该库存所订购的所有Bundles,并为该记录包括Bundles_Inventory.InventoryRequired?

In regards to @imran 关于@imran
Originally I had: 最初我有:

SELECT b.Id, b.Name, i.Id, i.Name, i.Stock, bi.InventoryRequired from         Bundles b
INNER JOIN Bundles_Inventory bi ON b.Id = bi.BundleId
INNER JOIN Inventory i ON bi.InventoryId = i.Id
WHERE b.ClientId = @clientId
ORDER BY i.Stock ASC  

But obviously this gets me duplicate data in regards to the Bundles table.. 但这显然使我获得了有关Bundles表的重复数据。

I then tried 然后我尝试了

SELECT TOP 1 b.Id, b.Name, i.Id, i.Name, i.Stock, bi.InventoryRequired from Bundles b
INNER JOIN Bundles_Inventory bi ON b.Id = bi.BundleId
INNER JOIN Inventory i ON bi.InventoryId = i.Id
WHERE b.ClientId = @clientId
ORDER BY i.Stock ASC  

And right now I'm trying to figure out how I can apply a Group By to figure this out. 现在,我正在尝试弄清楚如何应用Group By来解决这个问题。

You can do this with row_number() in most databases: 您可以在大多数数据库中使用row_number()进行此操作:

select b.*, i.*
from bundles b join
     (select i.*,
             row_number() over (partition by bi.bundleid order by i.stock desc) as seqnum
      from bundles_inventory bi join
           Inventory i 
           on bi.InventoryId = i.Id
     ) i
     on b.id = bi.bundleid 
where seqnum = 1;

You can add the where clause in the outer query. 您可以在外部查询中添加where子句。

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

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