[英]self join after an inner join
我正在寻找不同州的城市名称相同。 城市名称和 state 名称位于单独的表(城市和州)中,并且可以通过单独的公共列进行内部连接。
select c1.city, c1.state, c2.city, c2.state
from cities
inner join states on cities.commonid = states.commonid
内部加入后,我需要自我加入以执行 function,如下所示
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
我想知道如何自我加入一个表,该表是同一查询中另一个加入的结果 output 将是这样的
+----------+-------+--------+--------+
| city1 | state1|city2 |state2 |
+----------+-------+--------+--------+
| x | melb | x | syd |
| y | bris | y | ACT |
+----------+-------+--------+--------+
我假设表cities
有一个像state_id
这样的列,它引用表states
中的列state_id
(将名称更改为列的实际名称)。
首先对有条件的cities
进行自加入:
c1.city = c2.city AND c1.state_id < c2.state_id
<
运算符确保每对城市只返回一次。
然后加入 2 个states
副本,因为它们每个都将用于获取 2 个城市中每个城市的 state 的名称:
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
您可以对内部连接查询执行 select 并为其指定别名。
然后它会变成像下面这样......
Select c.city,c.state from
(Select City,state from cities inner join states where cities.id = states.id) as c
现在为 c 进行自我连接。
我将对拥有多个 state 的所有城市进行预查询。 然后加入 states 表,看看他们遇到了哪些状态。
select
Duplicates.city,
s.state
from
( select c1.city
from cities c1
group by c1.city
having count(*) > 1 ) Duplicates
JOIN cities c2
on Duplicates.city = c2.city
JOIN states s
on c2.commonid = s.commonid
order by
Duplicates.city,
s.state
通过不尝试仅对两个城市/州进行交叉表,您将获得一个列表。 如果一个城市名称存在于 5 个州,您打算如何显示它。 这样你会看到所有的字母。
我会建议一个CTE:
with cs as (
select c.name as city_name, s.name as state_name
from cities c join
states s
on c.commonid = s.commonid
)
select cs1.*, cs2.*
from cs cs1 join
cs cs2
on cs1.name = cs2.name and cs1.state <> cs2.state;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.