我有7张相同结构的表格。每个表有2列,其中一列是连接键(但不是主键),第二列是唯一的。
以下是2个表中提到的要求。但是我们需要开发7个表。
TAB1:
=====
CITY NAME
HYD RAMU
HYD KRISH
TAB1:
=====
CITY NAME
HYD RAJ
HYD KRISH
OUTPUT:
=======
CITY EXIST1 EXIST2
HYD RAMU NULL
HYD NULL RAJ
HYD KRISH KRISH
答案 0 :(得分:1)
4个表的答案 - 将其扩展到7个表格应该相当容易。
Oracle安装程序:
CREATE TABLE t1 ( city, name ) AS
SELECT 'a', 'a' FROM DUAL UNION ALL
SELECT 'a', 'b' FROM DUAL;
CREATE TABLE t2 ( city, name ) AS
SELECT 'a', 'a' FROM DUAL UNION ALL
SELECT 'a', 'c' FROM DUAL;
CREATE TABLE t3 ( city, name ) AS
SELECT 'a', 'b' FROM DUAL UNION ALL
SELECT 'a', 'd' FROM DUAL;
CREATE TABLE t4 ( city, name ) AS
SELECT 'a', 'a' FROM DUAL UNION ALL
SELECT 'a', 'e' FROM DUAL;
<强>查询强>:
SELECT COALESCE( t1.city, t2.city, t3.city, t4.city ) AS city,
t1.name AS exist1,
t2.name AS exist2,
t3.name AS exist3,
t4.name AS exist4
FROM t1
FULL OUTER JOIN t2
ON ( t1.city = t2.city
AND t1.name = t2.name )
FULL OUTER JOIN t3
ON ( COALESCE( t1.city, t2.city ) = t3.city
AND COALESCE( t1.name, t2.name ) = t3.name )
FULL OUTER JOIN t4
ON ( COALESCE( t1.city, t2.city, t3.city ) = t4.city
AND COALESCE( t1.name, t2.name, t3.name ) = t4.name );
<强>输出强>:
CITY EXIST1 EXIST2 EXIST3 EXIST4
---- ------ ------ ------ ------
a a a a
a b b
a c
a d
a e
答案 1 :(得分:0)
看起来你正在追踪FULL JOIN
:
SELECT COALESCE(t1.CITY, t2.CITY), t1.NAME AS EXIST1, t2.NAME AS EXIST2
FROM TAB1 AS t1
FULL JOIN TAB2 ON AS t2 ON t1.CITY = t2.CITY