vij*_*ker 1 mysql sql select join
当我遇到这个问题时,我正在尝试学习非对等连接。我有一张桌子流行音乐:
+------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| country | varchar(100) | YES | | NULL | |
| continent | varchar(100) | YES | | NULL | |
| population | bigint(20) | YES | | NULL | |
Run Code Online (Sandbox Code Playgroud)
我试图找到人口接近 100 的国家。
+------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| country | varchar(100) | YES | | NULL | |
| continent | varchar(100) | YES | | NULL | |
| population | bigint(20) | YES | | NULL | |
Run Code Online (Sandbox Code Playgroud)
我得到的输出是:
+------------+------------+------------+------------+
| country | country | population | population |
+------------+------------+------------+------------+
| pakistan | india | 99988 | 99999 |
| china | india | 99990 | 99999 |
| bangladesh | japan | 999 | 999 |
| india | pakistan | 99999 | 99988 |
| china | pakistan | 99990 | 99988 |
| japan | bangladesh | 999 | 999 |
| india | china | 99999 | 99990 |
| pakistan | china | 99988 | 99990 |
+------------+------------+------------+------------+
Run Code Online (Sandbox Code Playgroud)
正如我们所看到的,我得到了(印度,巴基斯坦)和(巴基斯坦,印度)对,这在数据上是一样的。是否可以从该对中消除其中一个记录?
您可以决定始终在 p1 端使用按字典顺序排列的第一个(或最后一个,为了论证起见)国家 - 使用<(或>) 代替<>. 另请注意,您的where子句是多余的,因为您在 的on子句中已经有了这个条件join:
select p1.country,
p2.country,
p1.population,
p2.population
from pops p1
inner join pops p2
on p1.population between p2.population - 100 and p2.population + 100 and
p1.country < p2.country
-- Here ------------------^
Run Code Online (Sandbox Code Playgroud)