![](/img/trans.png)
[英]How to select rows from another table if not enough rows in the first? With SQL
[英]select rows from SQL table and 5 rows from another
我有三個這樣的SQL Server表
我需要categories from LS_categoires where nodeid = 183
選擇categories from LS_categoires where nodeid = 183
並select only 5 files from LS_files
與每個類別相關的select only 5 files from LS_files
中select only 5 files from LS_files
如果我有兩個與node 183
有關的類別,結果應該是10 rows
嗎?
嘗試這個:
SELECT
*
FROM LS_Categories c
INNER JOIN
(
SELECT
*, ROW_NUMBER() OVER(PARTITION BY catid
ORDER BY item_id ASC) rownum
FROM LS_ItemTypes
) l ON c.catid = l.catid
AND l.rownum <= 5
INNER JOIN LS_Files f ON l.item_id = f.id
where c.nodeid = 183;
這將為每個類別選擇第一個文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.