【发布时间】:2021-06-28 23:32:46
【问题描述】:
鉴于下面的旅行表,from_city 和 to_city 有重复的条目。
| from_city | to_city | distance |
|---|---|---|
| NYC | BOS | 300 |
| BOS | NYC | 300 |
| OKC | BOS | 600 |
编写查询以仅检索唯一的组合,如下所示 -
| from_city | to_city | distance |
|---|---|---|
| NYC | BOS | 300 |
| OKC | BOS | 600 |
【问题讨论】:
鉴于下面的旅行表,from_city 和 to_city 有重复的条目。
| from_city | to_city | distance |
|---|---|---|
| NYC | BOS | 300 |
| BOS | NYC | 300 |
| OKC | BOS | 600 |
编写查询以仅检索唯一的组合,如下所示 -
| from_city | to_city | distance |
|---|---|---|
| NYC | BOS | 300 |
| OKC | BOS | 600 |
【问题讨论】:
假设您没有其他重复项,您可以使用:
select t.*
from t
where t.from_city < t.to_city or
not exists (select 1
from t t2
where t2.from_city = t.to_city and
t2.to_city = t.from_city
);
也就是说,选择按字母顺序排列的行。或者选择反向行不存在的行。
【讨论】: