3

我有以下查询:

select id from t1
intersect
select id from t2
intersect
select id from t3

id 在某些表中可能是非唯一的,所以我需要使用 distinct。

一般来说,什么更好:

select distinct id from (
select id from t1
intersect
select id from t2
intersect
select id from t3)

或者

select distinct id from t1
intersect
select id from t2 -- here id is unique
intersect
select distinct id from t3
4

1 回答 1

6

没有必要DISTINCT。运算符会自动生成一组不同的INTERSECT值。正如您在此示例中所看到的,x有两行 anID为 1,y只有一行 anID为 1,并且两者INTERSECTION中的 the 仅产生一行

SQL> ed
Wrote file afiedt.buf

  1  with x as (select 1 id from dual union all select 1 from dual),
  2       y as (select 1 id from dual)
  3  select id
  4    from x
  5  intersect
  6  select id
  7*   from y
SQL> /

        ID
----------
         1

即使您自己使用INTERSECT两行表,您仍然会在输出中获得单行

SQL> ed
Wrote file afiedt.buf

  1  with x as (select 1 id from dual union all select 1 from dual)
  2  select id
  3    from x
  4  intersect
  5  select id
  6*   from x
SQL> /

        ID
----------
         1
于 2012-08-08T09:07:30.620 回答