我有两张桌子:
COUNTRY (land_name, land_code)
CONTINENT (land_code, cont)
我需要创建两个查询:
获取位于两大洲的所有国家(假设这是唯一的可能性,
没有超过2个大陆的国家)。输出表单(land_name, Cont1, Cont2
)
我试图创建一个查询,至少从CONTINENT表中获取值:
SELECT land_code, MAX (cont) AS "K1", MIN(cont) AS "K2"
FROM CONTINENT
GROUP BY land_code;
但是在输出中我得到了所有国家的名单,即使他们只在一个大陆上
获取位于同一大洲的国家/地区(land_name1, land_name2, Cont1, Cont2
)
COUNTRIES (land_name, land_code, capital) Austria A Vienna Turkey TR Ankara Russia RU Moscow Italy I Rome France F Paris Egypt ET Cairo CONTINENTS (land_code, Continent, Percentage) ET Africa 90 ET Asia 10 F Europe 100 RU Asia 80 RU Europe 20 TR Asia 68 TR Europe 32
答案 0 :(得分:1)
1假设没有超过2个大陆的国家/地区,您可以使用此查询:
select land_name, cont1, cont2
from (select c.land_name, min(t.cont) cont1, max(t.cont) cont2
from country c join continent t on c.land_code = t.land_code group by c.land_name) t
where t.cont1 != t.cont2;
2同一大洲的所有国家/地区:
select distinct t1.land_name, t2.land_name, c.cont
from country t1
join country t2 on t1.land_name < t2.land_name
join continent c on c.land_code = t1.land_code
where t1.land_code = t2.land_code;
如果你需要展示两个大陆共同的国家,你可以试试这个:
select t1.land_name, t2.land_name, t1.cont1, t1.cont2
from (select c.land_name, min(t.cont) cont1, max(t.cont) cont2
from country c join continent t
on c.land_code = t.land_code
group by c.land_name) t1
join
(select c.land_name, min(t.cont) cont1, max(t.cont) cont2
from country c join continent t
on c.land_code = t.land_code
group by c.land_name) t2
on t1.land_name < t2.land_name
where t1.cont1 != t1.cont2
and t1.cont1 = t2.cont1 and t1.cont2 = t2.cont2;