mysql - 从列中提取子串并检查该子串是否与其他子串匹配

标签 mysql sql

我在处理一些 SQL 查询时遇到了一个问题。 在我的问题中,我有一个包含字段“名称”的表“世界”,问题是找出前三个首字母匹配的两个国家的名称,如澳大利亚 -> AUS 和奥地利 -> AUS,而不重复这些国家/地区。

SELECT a.name,SUBSTRING(a.name FROM 1 FOR 3) as cif,
b.name,SUBSTRING(b.name FROM 1 FOR 3) as cis
FROM world a,world b 
where a.name!=b.name 
group by a.name,b.name 
having cif=cis

结果:

name            cif name            cis
Australia       Aus Austria         Aus
Austria         Aus Australia       Aus
Bahamas         Bah Bahrain         Bah
Bahrain         Bah Bahamas         Bah
Belarus         Bel Belgium         Bel
Belarus         Bel Belize          Bel
Belgium         Bel Belarus         Bel
Belgium         Bel Belize          Bel
Belize          Bel Belarus         Bel
Belize          Bel Belgium         Bel
Burkina Faso    Bur Burma           Bur

在上面的结果中,你会看到一些国家在重复,比如第一行的澳大利亚与奥地利相匹配,而不应该与第二行的奥地利相匹配,结果应该是这样

结果:

name            cif name            cis
Australia       Aus Austria         Aus

Bahamas         Bah Bahrain         Bah

Belarus         Bel Belgium         Bel
Belarus         Bel Belize          Bel

Belgium         Bel Belize          Bel


Burkina Faso    Bur Burma           Bur

最佳答案

添加一个不等式:

SELECT a.name, SUBSTRING(a.name FROM 1 FOR 3) as cif, b.name, SUBSTRING(b.name FROM 1 FOR 3) as cis
FROM bbc a JOIN
     bbc b 
     ON a.name < b.name 
GROUP BY a.name, b.name 
HAVING cif = cis;

我不清楚是否需要GROUP BY。通常建议在聚合之前 进行过滤。我会将其简化为:

SELECT a.name, b.name, LEFT(b.name, 3) as first_3
FROM bbc a JOIN
     bbc b 
     ON a.name < b.name
WHERE LEFT(a.name, 3) = LEFT(b.name, 3) ;

如果有重复项,则使用 SELECT DISTINCTGROUP BY,但只有在原始数据中有重复项时才需要这样做。

关于mysql - 从列中提取子串并检查该子串是否与其他子串匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58166764/

相关文章:

php - 如何根据其他表列的 SUM 结果更新列?

mysql - MySQL EXPLAIN 中的 "filtered"列告诉我什么,我该如何使用它?

sql - 查询以根据今天的日期返回具有连续日期的行

python - 在 Django get_object_or_404 中选择特定字段

mysql - 数据库设计 : User Profiles like in Meetup. com

mysql - 亚马逊 RDS : can databases be setup in replicaton mode?

mysql - 如何从存储过程创建索引或在 MySQL 中的每个表上创建索引?

php - 我可以在 PHP 中混合使用 MySQL API 吗?

MySQL街道地址模糊搜索

sql - 组合 SUM 和 CASE 返回 0?