oracle sql创建组合相同的表而不重复

时间:2015-05-29 08:49:02

标签: sql oracle cartesian

我怎么解决这个问题? 我需要消除重复的笛卡尔积,一张桌子。 我想过使用“connect by”。感谢。

create table foo (
num number(2)
);

insert into foo values (1);
insert into foo values (2);
insert into foo values (3);

select a.num,b.num
from foo a, foo b;

NUM NUM
--- ---
 1   1 
 1   2 
 1   3 
 2   1 * duplicated
 2   2 
 2   3 
 3   1 * duplicated
 3   2 * duplicated
 3   3 

4 个答案:

答案 0 :(得分:3)

你可以试试这个:

select a.num,b.num
  from foo a cross join foo b
 where a.num <= b.num

答案 1 :(得分:1)

select a.num,b.num
from foo a, foo b
where a.num = b.num

答案 2 :(得分:1)

SQL Fiddle

Oracle 11g R2架构设置

create table foo ( num ) AS
SELECT LEVEL FROM DUAL CONNECT BY LEVEL <= 3;

查询1

select a.num,b.num
from foo a CROSS JOIN foo b
WHERE a.num <= b.num

<强> Results

| NUM | NUM |
|-----|-----|
|   1 |   1 |
|   1 |   2 |
|   1 |   3 |
|   2 |   2 |
|   2 |   3 |
|   3 |   3 |

答案 3 :(得分:1)

不需要交叉连接,因为您正在进行连接,您希望匹配表的第二个实例中的行,这些行的编号与表的第一个实例的编号相同或更大。这就是你如何阻止“重复”条目:

with foo as (SELECT LEVEL num FROM DUAL CONNECT BY LEVEL <= 3)
select f1.num f1_num,
       f2.num f2_num
from   foo f1
       join foo f2 on (f1.num <= f2.num);

    F1_NUM     F2_NUM
---------- ----------
         1          1
         1          2
         1          3
         2          2
         2          3
         3          3