我有两张表有多对多的关系。我需要加入他们并获得匹配的记录。
Table 1
Column1 | column 2| column 3|
1|p1|1.0
1|p1|1.1
1|p1|1.2
Table 2
Column1 | column 2| column 3|
1|p1|2.0
1|p1|2.1
1|p1|2.2
现在我希望结果为
1|p1|1.0|2.0
1|p1|1.1|2.1
1|p1|1.2|2.2
我的意思是column1和column2匹配并显示column3的两列中的值
编辑1: 尝试MT0查询后我遇到了一个问题。我对他的回答非常满意,但仍需要做一些改动:
Table 1
Column1 | column 2| column 3|
1|p1|1.0
1|p1|1.1
1|p1|1.2
Table 2
Column1 | column 2| column 3|
1|p1|1.0
1|p1|1.2
现在我希望结果为
1|p1|1.0|1.0
1|p1|1.1|NULL
1|p1|1.2|1.2
但我得到了
1|p1|1.0|1.0
1|p1|1.1|1.2
1|p1|1.2|NULL
请在此处提供帮助
答案 0 :(得分:2)
如果每个分区的行数不等,则可以执行以下操作:
Oracle安装程序:
CREATE TABLE table1 ( col1, col2, col3 ) AS
SELECT 1, 'P1', '1.0' FROM DUAL UNION ALL
SELECT 1, 'P1', '1.1' FROM DUAL UNION ALL
SELECT 1, 'P1', '1.2' FROM DUAL UNION ALL
SELECT 1, 'P2', '1.0' FROM DUAL UNION ALL
SELECT 1, 'P2', '1.2' FROM DUAL UNION ALL
SELECT 2, 'P1', '1.0' FROM DUAL;
CREATE TABLE table2 ( col1, col2, col3 ) AS
SELECT 1, 'P1', '2.0' FROM DUAL UNION ALL
SELECT 1, 'P1', '2.1' FROM DUAL UNION ALL
SELECT 1, 'P1', '2.2' FROM DUAL UNION ALL
SELECT 1, 'P2', '2.1' FROM DUAL UNION ALL
SELECT 2, 'P1', '2.0' FROM DUAL UNION ALL
SELECT 2, 'P1', '2.1' FROM DUAL;
<强>查询强>:
SELECT COALESCE( t1.col1, t2.col1 ) AS col1,
COALESCE( t1.col2, t2.col2 ) AS col2,
t1.col3 AS t1col3,
t2.col3 AS t2col3
FROM (
SELECT t.*,
ROW_NUMBER() OVER ( PARTITION BY col1, col2
ORDER BY col3 ) AS rn
FROM table1 t
) t1
FULL OUTER JOIN
(
SELECT t.*,
ROW_NUMBER() OVER ( PARTITION BY col1, col2
ORDER BY col3 ) AS rn
FROM table2 t
) t2
ON ( t1.col1 = t2.col1 AND t1.col2 = t2.col2 AND t1.RN = t2.rn )
ORDER BY col1, col2, t1col3 NULLS LAST, t2col3 NULLS LAST;
<强>输出强>:
COL1 COL2 T1COL3 T2COL3
---------- ---- ------ ------
1 P1 1.0 2.0
1 P1 1.1 2.1
1 P1 1.2 2.2
1 P2 1.0 2.1
1 P2 1.2
2 P1 1.0 2.0
2 P1 2.1
答案 1 :(得分:0)
您可以使用row_number
窗口函数添加带编号的计算列,并在连接中使用该列:
SELECT t1.column1, t2.column2, t1.column3, t2.column3
FROM (SELECT column1, column2, column3,
ROW_NUMBER() OVER (PARTITION BY column1, column2
ORDER BY column3) AS rn
FROM table1) t1
JOIN (SELECT column1, column2, column3,
ROW_NUMBER() OVER (PARTITION BY column1, column2
ORDER BY column3) AS rn
FROM table2) t2 ON t1.column1 = t2.column1 AND
t1.column2 = t2.column2 AND
t1.rn = t2.rn
答案 2 :(得分:0)
再创建一个列,只在两个表中都有匹配的ID,如
alter table 1
add column1 char(100)
alter table 2
add column2 char(100)
so table 1
Column1 | column 2| column 3|column4
1|p1|1.0
1|p1|1.1
1|p1|1.2
update table table1
set column4 = left(column1,4)
在表2中执行相同的操作,并将其用作左连接的键。
答案 3 :(得分:0)
请在下面试试。
1:
1 = y
2:
1 = y
3:
1 = y
4:
1 = y
5:
1 = y
6:
1 = z
16:
1 = y