表A:
parameter = request.GET['parameter']
parameter_1 = request.GET['parameter_1']
parameter_2 = request.GET['parameter_2']
表B:
ID NAME
---------
1 ABC
2 XYZ
**我需要一些类似的结果 表A的所有值均在表B中的表
ID NAME AID
----------------
1 ORANGE 1
2 APPLE 1
3 GUAVA 1
4 BANANA 2
5 CHICKO 2
答案 0 :(得分:0)
看起来您只需要两个表之间的内部联接:
WITH cte AS (
SELECT a.ID AS AID, a.NAME, b.ID AS BID,
ROW_NUMBER () OVER (PARTITION BY a.ID ORDER BY b.ID) rn
FROM tableA a
INNER JOIN tableB b
ON a.ID = b.AID
)
SELECT AID, NAME, BID
FROM cte
WHERE rn <= 2;
答案 1 :(得分:0)
您可以使用内部联接
select a.*, b.id as bid
from tableA a
join tableB b on a.id = b.aid
答案 2 :(得分:0)
尝试一下
----------SAMPLE DATA---------
DECLARE @TABLEA as TABLE (ID INT, NAME VARCHAR(100))
DECLARE @TABLEB AS TABLE (ID INT, NAME VARCHAR(100), AID INT)
INSERT INTO @TABLEA VALUES (1, 'ABC'),(2,'XYZ')
INSERT INTO @TABLEB VALUES (1, 'ORANGE', 1),(2, 'APPLE', 1),(3, 'GUAVA', 1),
(4, 'BANANA', 2),(5, 'CHICKO', 2)
------------SOLUTION-----------------
;WITH CTE AS
(
SELECT
a.ID as AID,
a.NAME,
b.ID,
ROW_NUMBER() OVER (PARTITION BY AID ORDER BY B.ID) as ROWNUMBER
FROM @TABLEA A
INNER JOIN @TABLEB B
ON A.ID = B.AID
)
SELECT AID, NAME, ID FROM CTE WHERE ROWNUMBER<=2
答案 3 :(得分:0)
您可以使用\left(
解决此问题。我倾向于在加入之前 :
row_number()
优化器可以为select a.*, b.id
from tableA a join
(select b.*, row_number() over (partition by aid order by b.id
from tableB b
) b
on a.id = b.aid
where b.seqnum <= 2;
和row_number()
使用索引。