2

下面是我试图运行的查询。

    select 
          from_country_id, 
          to_country_id, 
          fromCountry.country_name as from_country_name, 
          to_country_id.country_name as to_country_name
    from TourDetails t 
    left join country fromCountry on fromCountry.id = t. from_country_id
    left join country toCountry on toCountry.id = t. to_country_id

我有一个旅游详细信息表,我在其中保存来自国家/地区 ID 和国家/地区 ID。我有另一个国家表,其中包含国家 ID 和国家名称。

现在,当我查询 tourdetails 表时,我还需要获取国家名称。为此,我两次使用左连接和县表。

有什么办法我不必两次加入这个国家表,仍然得到来自国家和去往国家的国家名称?

4

4 回答 4

1

即使您无法优化查询,也有可能优化查询的执行。您应该检查查询的解释计划,如果它使用嵌套循环,则可能值得强制散列/*+USE_HASH(country) */

于 2012-07-18T11:00:45.693 回答
1

它归结为基于元组( [from, to] in tour)检索国家/地区详细信息(名称)。

据我所知,有可能与exists. 请查看以下是否适合您。

架构:

create table country (
  country_id varchar2(10)
);

create table tour
(
  from_country_id varchar2(10),
  to_country_id varchar2(10)
);

数据:

insert into country select 'AU' from dual;
insert into country select 'UA' from dual;
insert into country select 'UK' from dual;

insert into tour select 'AU', 'UA'  from dual;
insert into tour select 'UK', 'UA'  from dual;
insert into tour select 'UA', 'AU'  from dual;

解决方案本身:

select
  country_from.country_id from_, 
  country_to.country_id to_ 
from 
  country country_from,
  country country_to
where exists
  (select
     from_country_id, 
     to_country_id
   from tour 
   where 
     from_country_id = country_from.country_id 
    and 
     to_country_id = country_to.country_id)

不需要内部连接:-)

于 2012-07-18T11:23:59.243 回答
0

内连接有时比左连接运行得快得多。在对数据实施参照完整性的情况下,内连接和左连接将产生相同的结果。引用完整性意味着外键的每个实例都引用引用表中的现有行。

DBMS 可以通过数据定义中声明的约束来强制执行参照完整性。有时可行的替代方法是在加载新数据的过程中强制执行参照完整性。让 DBMS 强制执行参照完整性通常是可取的。

于 2012-07-18T11:15:35.637 回答
0

您可以通过一个连接来完成它,但代价是连接条件和代码中的or(or in) 可能不太清楚:

select t.from_country_id,
    t.to_country_id,
    max(case when c.id = from_country_id then c.country_name end)
        as from_country_name,
    max(case when c.id = to_country_id then c.country_name end)
        as to_country_name
from tourdetails t
join country c on c.id = t.from_country_id or c.id = t.to_country_id
group by t.from_country_id, t.to_country_id;

这和有两个连接之间可能没有太大的性能差异,您需要测试来检查。在这种情况下,取决于您所说的“优化”是什么意思。我想这里的风格可能更像是一个问题——在减少连接数量与对返回数据进行更复杂的操作之间进行权衡。

于 2012-07-18T12:02:51.177 回答