将多行子查询合并到相关的SQL查询中

时间:2018-06-28 12:06:24

标签: sql join correlated-subquery

我有一个相关的SQL子查询,该查询返回多行。例如,

SELECT NAME AS NAME1,
(SELECT NAME FROM ...) AS NAME2 /*this inner select returns more than one rows*/ 
FROM PERSONAL_INFORMATION

是否可以将NAME2返回的行与其余主查询(此处为NAME1)合并。 我在想什么是下面显示的交叉产品,在这里我可以使用GROUP BYDISTINCT将所有给定的实例分组?

NAME1_1  NAME2_1
NAME1_1  NAME2_2
NAME1_2  NAME2_1
NAME1_2  NAME2_2

1 个答案:

答案 0 :(得分:1)

然后只使用CROSS JOIN

SELECT I1.NAME AS NAME1, I2.NAME AS NAME2 
FROM PERSONAL_INFORMATION I1
CROSS JOIN PERSONAL_INFORMATION2 I2;

如果需要更多详细信息,可以使用GROUP BY

SELECT I1.NAME AS NAME1, I2.NAME AS NAME2, 
       COUNT(1) cnt, SUM(COL2) sum_col1 ...
FROM PERSONAL_INFORMATION I1
CROSS JOIN PERSONAL_INFORMATION2 I2
GROUP BY I1.NAME, I2.NAME;