Postgresql

選擇相關數據而不從子查詢中選擇外鍵

  • January 26, 2022

城市

您好,

我想通過輸入城市名稱來選擇相關縣的所有城市名稱。

我可以通過子查詢來做到這一點,但是還有其他方法可以實現嗎?

SELECT name
FROM cities
WHERE cities.county_id =
     (SELECT county_id
      FROM cities
      WHERE name = 'City1'
      LIMIT 1);

result => "City1, City2"

謝謝你。

您可以使用join

select name from cities c
inner join 
( SELECT county_id 
 FROM cities 
 WHERE name = 'City1' 
 LIMIT 1) as d 
on c.county_id=d.county_id ;

展示:http ://sqlfiddle.com/#!15/905fc/1

引用自:https://dba.stackexchange.com/questions/299319