如何在不使用任何条件的情况下连接所有表

时间:2016-09-01 07:17:46

标签: oracle11g

以下所有结果彼此无关,我们不能使用任何条件。

    ID
----------
     1
     2
     3
     4
     5
     6
     7

选择了7行。

NAME
-----------------
SRUJAN
DEERAJ
VINEETH
CHANIKYA
LAVANYA
KAVITHA
BUNNY

选择了7行。

   AGE
----------
    23
    24
    26
    25
    29
    28
    24

选择了7行。

 ADDRESS
 -------------
 NAGARAM
 BANDLAGUDA
 UPPAL
 KUKATPALLY
 HB COLONY
 MOULALI
 BOUDHA NAGAR

选择了7行。

SALARY
----------
 12000
 13000
 14000
 15000
 16000
 17000
 18000

选择了7行。

我使用

SQL>select id,name,age,address,salary from table1,table2,table3,table4,table5;

但显示选择了16807行

我想只获得一张桌子。 请提出建议。

2 个答案:

答案 0 :(得分:0)

只有1列且两者都没有关系的2个表之间唯一可能的连接是交叉连接。你无法避免它。当你试图加入时,你也会得到同样的结果。最好的方法是创建一个序列作为ID,然后在table2的select语句中调用它。

CREATE SEQUENCE TEST_SEQ 
  START WITH 1
  MAXVALUE 9999999999999999999999999999
  MINVALUE 1
  NOCYCLE;

select TEST_SEQ.nextval ID,col1 NAME
 from table2;

答案 1 :(得分:0)

这是一种使用内连接的方法。此解决方案将最低ID与字母顺序的第一个名称,最低年龄等匹配。

如果您需要随机匹配而不是此有序匹配,那么也很容易做到:在over...表的prep子句中,将order by子句更改为{{ 1}}(在所有地方)。

在下面的解决方案中,我只使用前三个表,但同样适用于任意数量的输入表。

order by dbms_random.value()

<强>输出

with
     tbl_id ( id ) as (
       select 1 from dual union all
       select 2 from dual union all
       select 3 from dual union all
       select 4 from dual union all
       select 5 from dual union all
       select 6 from dual union all
       select 7 from dual
     ),
     tbl_name ( name ) as (
       select 'SRUJAN'   from dual union all
       select 'DEERAJ'   from dual union all
       select 'VINEETH'  from dual union all
       select 'CHANIKYA' from dual union all
       select 'LAVANYA'  from dual union all
       select 'KAVITHA'  from dual union all
       select 'BUNNY'    from dual
     ),
     tbl_age ( age ) as (
       select 23 from dual union all
       select 24 from dual union all
       select 26 from dual union all
       select 25 from dual union all
       select 29 from dual union all
       select 28 from dual union all
       select 24 from dual
     ),
     prep_id ( id, rn ) as (
       select id, row_number() over (order by id) from tbl_id
     ),
     prep_name ( name, rn ) as (
       select name, row_number() over (order by name) from tbl_name
     ),
     prep_age ( age , rn ) as (
       select age, row_number() over (order by age) from tbl_age
     )
select i.id, n.name, a.age
from   prep_id i inner join prep_name n on i.rn = n.rn
                 inner join prep_age  a on i.rn = a.rn
;