mysql - 如何优化left join的sql?

标签 mysql left-join

我有两个表phonephone_area

电话列:

  1. id: pk

  2. phone: unique index

电话数据:

|id| phone       |
+--+-------------+
|1 | 1882601xxxx |
+--+-------------+
|2 | 1882602xxxx |
+--+-------------+
|2 | 1882602xxxx |
+--+-------------+
|2 | 1882603xxxx  | 
+--+-------------+

phone_area 列:

1.id: pk

2.phone: unique index

3.area: varchar(20)

phone_area数据:

|id| phone  |  area    |  
+--+--------+----------+
|1 | 1882601|  area_one|
+--+--------+----------+
|2 | 1882602|  area_two|
+--+--------+----------+ 
|2 | 1882603|area_three|
+--+--------+----------+

我的 sql 如下:

SELECT t1.phone,t2.area FROM phone t1
LEFT JOIN phone_area t2 ON substr(t1.phone, 1, 7)= t2.phone

它很慢。

在解释sql时,显示type为"ALL"和Using where;使用连接缓冲区( block 嵌套循环)

如何改进我的sql?

最佳答案

按照以下步骤:

ALTER TABLE phone ADD phone_cut int; --add a new column

UPDATE phone SET phone_cut = substr(phone, 1, 7); --store the cropped value of phone

ALTER TABLE phone ADD INDEX ind_name (phone_cut); -- add an index on that column

然后:

SELECT t1.phone,t2.area FROM phone t1
LEFT JOIN phone_area t2
 ON t1.phone_cut= t2.phone

关于mysql - 如何优化left join的sql?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37807801/

相关文章:

php - 使用 PHP 在不同的时区回显 MySQL 时间戳

php - 使用 PHP 将数据输入 MySQL 数据库时遇到问题

涉及join的MySQL select语句

mysql - Left Join/IS NULL 如何消除一个表中存在而另一个表中没有的记录?

mysql - 子查询似乎不起作用

mysql当年与当年+6个月

java - 关于mysql中的Query语句

SQL 计数()/左连接?

mysql - 使用 GROUP CONCAT 和 LEFT JOIN 计算行的总和

php - 循环通过 MySQL 左加入 php 与 2 个单独的查询