![](/img/trans.png)
[英]Selecting the top matching record of a one to many relationship on a SQL join statement
[英]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.