在 SQL 中加入 2 Table 个变量
Join 2 Table Variables in SQL
如何连接不包含外键列的 2 table 个变量。
DECLARE @InventoryIDList TABLE(ID INT)
DECLARE @ProductSupplierIDList TABLE(ID INT)
异常输出
@InventoryList
--------------
123
456
789
111
@ProductSupplierIDList
--------------
999
888
777
666
@InventoryList ProductSupplierIDList
---------------------------------------
123 | 999
567 | 888
789 | 777
111 | 666
都是随机数据。我只想将 2 table 变量组合成上面的样子。我尝试了所有类型的连接。但是我需要在没有 null
值的情况下获得上面提到的输出。
我尝试了 CROSS APPLY
SELECT *
FROM @InventoryIDList invList CROSS APPLY @ProductSupplierIDList prdList
但是它给了我 5^2 个元素作为重复的结果。
我猜你需要 Row_Number
和 Full Outer Join
,考虑到这两个表之间没有关系
SELECT I.ID,
P.ID
FROM (SELECT Rn = Row_number()OVER(ORDER BY ID),*
FROM @InventoryList) I
FULL JOIN (SELECT Rn = Row_number()OVER(ORDER BY ID),*
FROM @ProductSupplierIDList) p
ON I.RN = P.RN
假设 JOIN
条件相同 "row number" ID 升序:
WITH invList AS (
SELECT *,
ROW_NUMBER() OVER (ORDER BY ID) AS RN
FROM @InventoryIDList),
prdList AS (
SELECT *,
ROW_NUMBER() OVER (ORDER BY ID) AS RN
FROM @ProductSupplierIDList)
SELECT *
FROM invList IL
JOIN prdList PL ON IL.RN = PL.RN;
由于 ID 不是按顺序排列的,可以是随机的,我建议在 table 变量上使用身份并加入:
DECLARE @InventoryIDList TABLE(JoiningID INT IDENTITY(1,1), ID INT)
DECLARE @ProductSupplierIDList TABLE(JoiningID INT IDENTITY(1,1), ID INT)
INSERT INTO @InventoryIDList
VALUES
(123),
(456),
(789),
(111)
INSERT INTO @productsupplierIDList
VALUES
(999),
(888),
(777),
(666)
SELECT i.id, p.id
FROM @inventoryIDList i
INNER JOIN @productsupplierIDList p
oN i.joiningid = p.JoiningID
如何连接不包含外键列的 2 table 个变量。
DECLARE @InventoryIDList TABLE(ID INT)
DECLARE @ProductSupplierIDList TABLE(ID INT)
异常输出
@InventoryList
--------------
123
456
789
111
@ProductSupplierIDList
--------------
999
888
777
666
@InventoryList ProductSupplierIDList
---------------------------------------
123 | 999
567 | 888
789 | 777
111 | 666
都是随机数据。我只想将 2 table 变量组合成上面的样子。我尝试了所有类型的连接。但是我需要在没有 null
值的情况下获得上面提到的输出。
我尝试了 CROSS APPLY
SELECT *
FROM @InventoryIDList invList CROSS APPLY @ProductSupplierIDList prdList
但是它给了我 5^2 个元素作为重复的结果。
我猜你需要 Row_Number
和 Full Outer Join
,考虑到这两个表之间没有关系
SELECT I.ID,
P.ID
FROM (SELECT Rn = Row_number()OVER(ORDER BY ID),*
FROM @InventoryList) I
FULL JOIN (SELECT Rn = Row_number()OVER(ORDER BY ID),*
FROM @ProductSupplierIDList) p
ON I.RN = P.RN
假设 JOIN
条件相同 "row number" ID 升序:
WITH invList AS (
SELECT *,
ROW_NUMBER() OVER (ORDER BY ID) AS RN
FROM @InventoryIDList),
prdList AS (
SELECT *,
ROW_NUMBER() OVER (ORDER BY ID) AS RN
FROM @ProductSupplierIDList)
SELECT *
FROM invList IL
JOIN prdList PL ON IL.RN = PL.RN;
由于 ID 不是按顺序排列的,可以是随机的,我建议在 table 变量上使用身份并加入:
DECLARE @InventoryIDList TABLE(JoiningID INT IDENTITY(1,1), ID INT)
DECLARE @ProductSupplierIDList TABLE(JoiningID INT IDENTITY(1,1), ID INT)
INSERT INTO @InventoryIDList
VALUES
(123),
(456),
(789),
(111)
INSERT INTO @productsupplierIDList
VALUES
(999),
(888),
(777),
(666)
SELECT i.id, p.id
FROM @inventoryIDList i
INNER JOIN @productsupplierIDList p
oN i.joiningid = p.JoiningID