MySQL Count Distinct值的处理速度很慢。如何加快它?
要加快进程,可以使用INDEX。让我们首先创建一个表 -
mysql> create table DemoTable1905 ( FirstName varchar(20), LastName varchar(20) , INDEX F_L_Name(FirstName,LastName) ); Query OK, 0 rows affected (0.00 sec)
使用insert命令向表中插入一些记录 -
mysql> insert into DemoTable1905 values('John','Smith'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1905 values('John','Doe'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1905 values('Adam','Smith'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1905 values('John','Doe'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1905 values('Chris','Brown'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1905 values('Adam','Smith'); Query OK, 1 row affected (0.00 sec)
使用select语句显示表中的所有记录 -
mysql> select * from DemoTable1905;
这会产生以下输出 -
+-----------+----------+ | FirstName | LastName | +-----------+----------+ | Adam | Smith | | Adam | Smith | | Chris | Brown | | John | Doe | | John | Doe | | John | Smith | +-----------+----------+ 6 rows in set (0.00 sec)
以下是计算不同值的方法 -
mysql> select count(distinct FirstName) from DemoTable1905;
这会产生以下输出 -
+---------------------------+ | count(distinct FirstName) | +---------------------------+ | 3 | +---------------------------+ 1 row in set (0.00 sec)
广告