oracle交叉口有无明显

mic*_*nko 2 sql oracle query-optimization

我有以下查询:

select id from t1
intersect
select id from t2
intersect
select id from t3
Run Code Online (Sandbox Code Playgroud)

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

总的来说更好的是:

select distinct id from (
select id from t1
intersect
select id from t2
intersect
select id from t3)
Run Code Online (Sandbox Code Playgroud)

要么

select distinct id from t1
intersect
select id from t2 -- here id is unique
intersect
select distinct id from t3
Run Code Online (Sandbox Code Playgroud)

Jus*_*ave 5

没有必要DISTINCT.的INTERSECT操作者自动生成一组不同的值.正如您在此示例中所看到的,x有两行,其中一ID行为1,y只有一ID行为1 INTERSECTION,而两行中只有一行

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
Run Code Online (Sandbox Code Playgroud)

即使你自己使用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
Run Code Online (Sandbox Code Playgroud)