我需要从一些已连接的表中选择一些设置,但前提是Items ORDER BY EndTime DESC
ItemID
在前1000个项目中。
这样做我构建了以下查询,虽然肯定可以改进,但是有效:
SELECT ss.ModuleCode, ss.MaxItems , w.*
FROM Subscriptions ss
JOIN Sellers s ON s.UID=ss.UID
JOIN Items i ON s.UserID=i.UserID
JOIN Items ii ON i.ItemID=ii.ItemID
JOIN Modules mo ON ss.ModuleCode=mo.ModuleCode
JOIN Settings w ON w.UID=s.UID AND ss.ModuleCode=w.WCode
FULL JOIN GoogleFonts f ON f.FontCode=a.FontFamily
JOIN ( SELECT
ItemID
FROM Items
WHERE UserID=@UserID
ORDER BY EndTime DESC
OFFSET 0 ROWS
FETCH FIRST (1000) ROWS ONLY
) it ON it.ItemID=i.ItemID
WHERE it.ItemID=@ItemID
AND .....
但由于MaxItems并不总是1000且其值由ss.MaxItems定义, 我会用ss.MaxItems的动态值替换1000的固定值,但我还没有办法做到这一点:
虽然不是最佳,因为使查询更重,我尝试用这个结果代替1000进一步查询:
SELECT ss.ModuleCode, ss.MaxItems , w.*
FROM Subscriptions ss
JOIN Sellers s ON s.UID=ss.UID
JOIN Items i ON s.UserID=i.UserID
JOIN Items ii ON i.ItemID=ii.ItemID
JOIN Modules mo ON ss.ModuleCode=mo.ModuleCode
JOIN Settings w ON w.UID=s.UID AND ss.ModuleCode=w.WCode
FULL JOIN GoogleFonts f ON f.FontCode=a.FontFamily
JOIN ( SELECT
ItemID
FROM Items
WHERE UserID=@UserID
ORDER BY EndTime DESC
OFFSET 0 ROWS
FETCH FIRST ( SELECT ss.MaxItems
FROM Subscriptions ss
JOIN Sellers s ON s.UID=ss.UID
JOIN Items i ON s.UserID=i.UserID
JOIN Modules mo ON ss.ModuleCode=mo.ModuleCode
JOIN Settings w ON w.UID=s.UID AND ss.ModuleCode=w.WCode
WHERE i.ItemID=@ItemID) ROWS ONLY
) it ON it.ItemID=i.ItemID
Where it.ItemID=@ItemID
AND .....
但由于这会返回超过1的值,因此不会被接受:限制为TOP 1结果,最新的子查询将起作用,但不会根据需要完全动态。
可以建议如何解决或至少建议解决方案的路径?
谢谢!
答案 0 :(得分:2)
而不是fetch
使用row_number
:
JOIN (SELECT ItemID, ROW_NUMBER() OVER (PARTITION BY UserID ORDER BY EndTime) as seqnum
FROM Items it
WHERE UserID = @UserID
) it
ON it.ItemID = i.ItemID AND seqnum <= ss.maxitems