mysql> select * from tb_users; +--------+----------+------------+------------+ | userid | username | birth | last_login | +--------+----------+------------+------------+ | 10000 | Allen | 1981-01-01 | 2014-02-02 | | 10001 | Ben | 1982-04-02 | 2014-04-30 | | 10002 | Curry | 1985-08-12 | 2014-01-17 | | 10003 | Davis | 1978-07-12 | 2014-09-20 | | 10004 | Ellis | 1979-09-02 | 2015-02-10 | | 10005 | Faried | 1984-02-05 | 2014-12-01 | | 10007 | Hamilton | 1988-07-07 | 2014-11-16 | | 10008 | Johnson | 1986-06-07 | 2015-01-23 | | 10009 | Jackson | 1989-08-17 | 2013-12-23 | | 10010 | James | 1984-12-30 | 2014-12-23 | | 10011 | Gay | 1987-02-03 | 2014-12-23 | | 10012 | Kaman | 1981-04-04 | 2010-01-13 | | 10006 | Wade | 1982-03-04 | 2012-05-19 | +--------+----------+------------+------------+ 13 rows in set (0.00 sec) mysql>主键是一种特殊的唯一索引,不允许有空值,一般在创建表时同时创建主键索引。一个表只能有一个主键。create unique index idx_name on tb_users(username(5)); Query OK, 13 rows affected (0.13 sec) Records: 13 Duplicates: 0 Warnings: 0 mysql>
一般来说应该在这些列上创建索引: 经常需要搜索的列(加快搜索速度)、经常用于连接的列(加快连接速度)、经常需要根据范围进行搜索的列、经常需要排序的列、经常使用在where子句中的列上。