我正在寻找在不同州有相同名称的城市。城市名称和州名称位于单独的表(城市和州)中,并且可以通过单独的公共列进行内部连接。
select c1.city, c1.state, c2.city, c2.state
from cities
inner join states on cities.commonid = states.commonid
内部加入后,我需要自我加入以执行如下功能
select c1.city, c1.state, c2.city, c2.state
from *joined table* c1 join
*joined table* c2
on c1.city = c2.city and c1.state <> c2.state
我想知道如何自连接一个表,该表是同一查询输出中另一个连接的结果,将是这样的
+----------+-------+--------+--------+
| city1 | state1|city2 |state2 |
+----------+-------+--------+--------+
| x | melb | x | syd |
| y | bris | y | ACT |
+----------+-------+--------+--------+
我认为该表cities
具有像列state_id
引用的列state_id
在表中states
(改名字列的实际名称)。
首先cities
对条件进行自联接:
c1.city = c2.city AND c1.state_id < c2.state_id
该<
运营商可以确保每对城市的西港岛线只返回一次。
然后加入 2 个副本states
,因为每个副本都将用于获取 2 个城市中每个城市的州名称:
SELECT c1.city city1, s1.state state1,
c2.city city2, s2.state state2
FROM cities c1
INNER JOIN cities c2 ON c1.city = c2.city AND c1.state_id < c2.state_id
INNER JOIN states s1 ON s1.state_id = c1.state_id
INNER JOIN states s2 ON s2.state_id = c2.state_id
ORDER BY city1
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句