如何改进 MySQL 中的 select 查询以提升速度?
要加快查询速度,使用 MySQL IN(),因为它内部使用了索引。首先,让我们创建一个表:
mysql> create table DemoTable1618 -> ( -> ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> ClientName varchar(20), -> ClientEmailId varchar(30) -> ); Query OK, 0 rows affected (1.53 sec)
使用插入命令在表中插入一些记录
mysql> insert into DemoTable1618(ClientName,ClientEmailId) values('Chris Brown','[email protected]'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable1618(ClientName,ClientEmailId) values('David Miller','[email protected]'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable1618(ClientName,ClientEmailId) values('John Doe','[email protected]'); Query OK, 1 row affected (0.28 sec) mysql> insert into DemoTable1618(ClientName,ClientEmailId) values('John Smith','[email protected]'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable1618(ClientName,ClientEmailId) values('Adam Smith','[email protected]'); Query OK, 1 row affected (0.17 sec)
使用 `select` 语句从表中显示所有记录:
mysql> select * from DemoTable1618;
这将生成以下输出:
+----------+--------------+-------------------------+ | ClientId | ClientName | ClientEmailId | +----------+--------------+-------------------------+ | 1 | Chris Brown | [email protected] | | 2 | David Miller | [email protected] | | 3 | John Doe | [email protected] | | 4 | John Smith | [email protected] | | 5 | Adam Smith | [email protected] | +----------+--------------+-------------------------+ 5 rows in set (0.00 sec)
下面是使用 IN() 加快查询速度的查询:
mysql> select * from DemoTable1618 where ClientEmailId IN('[email protected]','[email protected]','[email protected]');
这将生成以下输出:
+----------+--------------+-------------------------+ | ClientId | ClientName | ClientEmailId | +----------+--------------+-------------------------+ | 2 | David Miller | [email protected] | | 3 | John Doe | [email protected] | | 4 | John Smith | [email protected] | +----------+--------------+-------------------------+ 3 rows in set (0.00 sec)
广告