Mysql:过滤表依赖于不同表中列的子字符串
Posted
技术标签:
【中文标题】Mysql:过滤表依赖于不同表中列的子字符串【英文标题】:Mysql: Filter table depend on subtring from column in different table 【发布时间】:2021-08-10 08:53:44 【问题描述】:我的数据库中有 2 个表。
1- 客户表。
+-----------+--------------------------------+
| customers | CREATE TABLE `customers` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`phone` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
KEY `customers_phone_index` (`phone`)
) ENGINE=InnoDB AUTO_INCREMENT=42 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci |
+-----------+--------------------------------+
===>客户表中的数据示例
+----+----------------------------------------+-----------------+
| id | name | phone |
+----+----------------------------------------+-----------------+
| 1 | Frehiwot Teka | (251) 988200000 |
| 2 | Fanetahune Abaia | (251) 924418461 |
| 3 | Yonatan Tekelay | (251) 911168450 |
| 4 | EMILE CHRISTIAN KOUKOU DIKANDA HONORE | (237) 697151594 |
| 5 | MICHAEL MICHAEL | (237) 677046616 |
| 6 | ARREYMANYOR ROLAND TABOT | (237) 6A0311634 |
| 7 | Edunildo Gomes Alberto | (258) 847651504 |
| 8 | Walla's Singz Junior | (258) 846565883 |
| 9 | sevilton sylvestre | (258) 849181828 |
+----+----------------------------------------+-----------------+
2- 国家/地区表。
+-----------+--------------------------------+
countries | CREATE TABLE `countries` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(80) COLLATE utf8mb4_unicode_ci NOT NULL,
`numcode` smallint DEFAULT NULL,
`phonecode` int NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=254 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci |
+-----------+--------------------------------+
===>国家表中的数据示例。
+----+----------------+---------+-----------+
| id | name | numcode | phonecode |
+----+----------------+---------+-----------+
| 1 | Cameroon | 120 | 237 |
| 2 | Ethiopia | 231 | 251 |
| 3 | Mozambique | 508 | 258 |
| 4 | American Samoa | 16 | 1684 |
| 5 | Andorra | 20 | 376 |
| 6 | Angola | 24 | 244 |
+-----+---------------+---------+-----------+
==> 我需要获取带有国家名称和代码的电话号码列表。
==> 输出示例
+------------+--------------+--------------+
| country | country_code | phone_number |
+------------+--------------+--------------+
| Cameroon | 237 | 6A0311634 |
| Cameroon | 237 | 697151594 |
| Cameroon | 237 | 677046616 |
| Ethiopia | 251 | 924418461 |
| Ethiopia | 251 | 911168450 |
| Mozambique | 258 | 849181828 |
| Mozambique | 258 | 847651504 |
| Mozambique | 258 | 846565883 |
+------------+--------------+--------------+
【问题讨论】:
您需要规范化您的数据,例如通过将电话号码中的国家代码移动到单独的列中。这将比在查询中使用regular expressions 容易得多,这会使查询执行得更慢。.. FROM customers JOIN countries ON SUBSTRING_INDEX(SUBSTRING(phone FROM 2), ')', 1) = phonecode ..
【参考方案1】:
在 mysql 中,可以这样表达:
select c.*,
co.country, substring_index(co.phone, ' ', -1) as phone_number
from customers c left join
countries co
on c.phone like concat('(', co.phone, ')%');
【讨论】:
以上是关于Mysql:过滤表依赖于不同表中列的子字符串的主要内容,如果未能解决你的问题,请参考以下文章
在不选择所需列的情况下加入表或加入表中列的子选择是不是更有效