簡體   English   中英

選擇與自定義聯接表成多對多關系的第一行

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

我在MM關系中有三個表:

在此處輸入圖片說明

我在嘗試找出如何僅使用Inventory.Stock ASC訂購的第一個相關庫存項目來檢索所有Bundle時遇到很多麻煩,而且還返回Bundles_Inventory.InventoryRequired字段。

我已經看到了對類似問題的其他回答,但是沒有一個考慮到自定義聯接表。

如何選擇該庫存所訂購的所有Bundles,並為該記錄包括Bundles_Inventory.InventoryRequired?

關於@imran
最初我有:

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  

但這顯然使我獲得了有關Bundles表的重復數據。

然后我嘗試了

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  

現在,我正在嘗試弄清楚如何應用Group By來解決這個問題。

您可以在大多數數據庫中使用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;

您可以在外部查詢中添加where子句。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM