sql - 如何优化以下 Oracle 查询以仅在一个连接中获取出发地和目的地国家/地区名称?

标签 sql oracle

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

    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表时,我还需要获取国家/地区名称。为此,我对国家表使用左连接两次。

有什么方法可以让我不必两次加入该国家/地区表,并且仍然可以获得出发国家/地区和目的地国家/地区的国家/地区名称吗?

最佳答案

归结为根据元组(旅游中的 [from, to])检索国家/地区详细信息(名称)。

据我所知,可以使用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)

不需要内部联接:-)

关于sql - 如何优化以下 Oracle 查询以仅在一个连接中获取出发地和目的地国家/地区名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11539500/

相关文章:

mysql - 修改列与删除和添加列 Mysql

MySQL 查询列名子字符串

sql - 在哪里可以找到有关 ODBC SQL 方言/语法的信息,包括。内置函数/运算符?

sql - 在 SELECT 语句中排序下一个值

sql - 是否可以在 Oracle 中将表名作为参数传递?

sql - 如何根据计算获得百分位排名

mysql - 不同数据库类型的示例数据库模式

使用限制时mysql查询速度变慢

arrays - 在 PL-SQL 中循环之前缓存数组长度

java - 如何保存小程序的数据?