mysql> select database();
+------------+
| database() |
+------------+
| sakila |
+------------+
1 row in set (0.00 sec)
mysql> create table city_demo (city varchar(50) not null);
mysql> insert into city_demo (city) select city from city; --执行两次
Query OK, 600 rows affected (0.02 sec)
Records: 600 Duplicates: 0 Warnings: 0
mysql> update city_demo set city = ( select city from city order by rand() limit 1);
Query OK, 1198 rows affected (0.42 sec)
Rows matched: 1200 Changed: 1198 Warnings: 0
注:因为上述sql语句使用了rand函数,所以每个人的执行结果可以都不一样!
首先找到最常见的城市列表:
mysql
>
select count(*) as cnt,city from city_demo group by city order by cnt desc limit 10;
+-----+---------------+
| cnt | city |
+-----+---------------+
| 8 | Dongying |
| 7 | Omdurman |
| 6 | Etawah |
| 6 | Okara |
| 6 | Tsuyama |
| 6 | Brindisi |
| 6 | Kuwana |
| 6 | Grand Prairie |
| 5 | Fuyu |
| 5 | Siegen |
+-----+---------------+
10 rows in set (0.00 sec)
现在查找到频繁出现的城市前缀。先从3个前缀字母开始,然后4个,5个,6个:
mysql
>
select count(*) as cnt,left(city,3) as pref from city_demo group by pref order by cnt desc limit 10;
+-----+------+
| cnt | pref |
+-----+------+
| 23 | San |
| 15 | Hal |
| 14 | Cha |
| 14 | al- |
| 12 | Bat |
| 12 | Kor |
| 11 | Don |
| 11 | Shi |
| 10 | La |
| 10 | El |
+-----+------+
10 rows in set (0.00 sec)
mysql
>
select count(*) as cnt,left(city,4) as pref from city_demo group by pref order by cnt desc limit 10;
+-----+------+
| cnt | pref |
+-----+------+
| 14 | San |
| 8 | Dong |
| 7 | Iwak |
| 7 | al-Q |
| 7 | Omdu |
| 6 | Kuwa |
| 6 | Tsuy |
| 6 | Brin |
| 6 | Etaw |
| 6 | Okar |
+-----+------+
10 rows in set (0.00 sec)
可以看到3字节检索到的结果与全文检索相差很大,继续增加到4个字节
mysql
>
select count(*) as cnt,left(city,5) as pref from city_demo group by pref order by cnt desc limit 10;
+-----+-------+
| cnt | pref |
+-----+-------+
| 8 | Dongy |
| 7 | al-Qa |
| 7 | Omdur |
| 6 | Okara |
| 6 | Valle |
| 6 | Grand |
| 6 | Tsuya |
| 6 | Etawa |
| 6 | South |
| 6 | Kuwan |
+-----+-------+
10 rows in set (0.00 sec)
mysql
>
select count(*) as cnt,left(city,6) as pref from city_demo group by pref order by cnt desc limit 10;
+-----+--------+
| cnt | pref |
+-----+--------+
| 8 | Dongyi |
| 7 | Omdurm |
| 6 | Okara |
| 6 | Tsuyam |
| 6 | Valle |
| 6 | Grand |
| 6 | Etawah |
| 6 | Brindi |
| 6 | Kuwana |
| 5 | Haldia |
+-----+--------+
10 rows in set (0.01 sec)
mysql
>
explain select * from city_demo where city like 'Jin%' \G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: city_demo
partitions: NULL
type: range
possible_keys: city
key: city
key_len: 8
ref: NULL
rows: 4
filtered: 100.00
Extra: Using where
1 row in set, 1 warning (0.00 sec)