如何对一张表进行一次联接,而不是对该表进行 2 次联接

问题描述 投票:0回答:1

我需要位置表上的城市名称和国家/地区名称值。 下面,我通过在同一个表上使用 2 个连接来达到这些值

但是如何在同一张表上使用 1 个连接而不是 2 个连接来做到这一点?

我需要学习有效的解决方案?

select cus.*, l.name As 'City Name', lo.name As 'CountryName' 
from Customer cus
left JOIN Location l ON l.id= cus.cityId
left JOIN Location lo ON lo.id= cus.countryId
sql left-join
1个回答
0
投票

位置表在同一列中同时包含 cityID 和 CountryID 值,这是一种奇怪的模式。当您使用

conditional aggregation
以及
cartesian join
时,这是可行的。然而,我可能只使用两个连接,因为它更容易阅读。

create table customer (
  id integer, 
  name varchar(10), 
  cityId varchar(10), 
  countryId varchar(10)
  );
  
create table location (
  id varchar(10), 
  name varchar(20)
  );
  
insert into customer values 
(1, 'John', 'ci101', 'co501'), 
(2, 'Sally', 'ci102', 'co502'), 
(3, 'Henry', 'ci103', 'co503');

insert into location values 
('ci101', 'Paris'), 
('ci102', 'Miami'), 
('co501', 'France'), 
('co502', 'United States'),
('co503', 'Spain');

select cus.id, 
 cus.name, 
 cus.cityId, 
 max(case when cus.cityId = l.id then l.name end) as city_name,
 cus.countryId,
 max(case when cus.countryId = l.id then l.name end) as country_name
from customer cus, location l
group by 1,2,3,5
order by 1,2;
id 名字 城市ID 城市名称 国家/地区 国家/地区名称
1 约翰 ci101 巴黎 co501 法国
2 莎莉 ci102 迈阿密 co502 美国
3 亨利 ci103 co503 西班牙

© www.soinside.com 2019 - 2024. All rights reserved.