如何优化左连接的sql?
How to optimize sql of left join?
我有两个tablephone和phone_area
phone 列:
id: pk
phone: unique index
phone数据:
|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;使用连接缓冲区(块嵌套循环)
如何提高我的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
我有两个tablephone和phone_area
phone 列:
id: pk
phone: unique index
phone数据:
|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;使用连接缓冲区(块嵌套循环)
如何提高我的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