MySQL 查询获取唯一值的数量?

mysqlmysqli database

要计算列上的唯一值,您需要使用关键字 DISTINCT。要了解如何执行此操作,让我们创建一个表。创建表的查询如下−

mysql> create table UniqueCountByIPAddress
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> UserHits int,
   -> UserIPAddress varchar(50),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.69 sec)

使用 insert 命令在表中插入一些记录。 查询语句如下 −

mysql> insert into UniqueCountByIPAddress(UserHits,UserIPAddress) values(10,'127.0.0.1');
Query OK, 1 row affected (0.20 sec)
mysql> insert into UniqueCountByIPAddress(UserHits,UserIPAddress) values(10,'127.0.0.1');
Query OK, 1 row affected (0.20 sec)
mysql> insert into UniqueCountByIPAddress(UserHits,UserIPAddress) values(20,'127.0.0.1');
Query OK, 1 row affected (0.20 sec)
mysql> insert into UniqueCountByIPAddress(UserHits,UserIPAddress) values(20,'127.0.0.1');
Query OK, 1 row affected (0.17 sec)
mysql> insert into UniqueCountByIPAddress(UserHits,UserIPAddress) values(20,'127.0.0.2');
Query OK, 1 row affected (0.13 sec)
mysql> insert into UniqueCountByIPAddress(UserHits,UserIPAddress) values(20,'127.0.0.2');
Query OK, 1 row affected (0.20 sec)
mysql> insert into UniqueCountByIPAddress(UserHits,UserIPAddress) values(30,'127.0.0.2');
Query OK, 1 row affected (0.17 sec)
mysql> insert into UniqueCountByIPAddress(UserHits,UserIPAddress) values(30,'127.0.0.2');
Query OK, 1 row affected (0.28 sec)
mysql> insert into UniqueCountByIPAddress(UserHits,UserIPAddress) values(30,'127.0.0.2');
Query OK, 1 row affected (0.14 sec)

使用 select 语句显示表中的所有记录。查询如下 −

mysql> select *from UniqueCountByIPAddress;

以下是输出 −

+----+----------+--------------+
| Id | UserHits | UserIPAddress|
+----+----------+--------------+
|  1 |       10 | 127.0.0.1    |
|  2 |       10 | 127.0.0.1    |
|  3 |       20 | 127.0.0.1    |
|  4 |       20 | 127.0.0.1    |
|  5 |       20 | 127.0.0.2    |
|  6 |       20 | 127.0.0.2    |
|  7 |       30 | 127.0.0.2    |
|  8 |       30 | 127.0.0.2    |
|  9 |       30 | 127.0.0.2    |
+----+----------+--------------+

以下是计算‘UserIPAddress’列中不同值的查询。 −

mysql> select UserHits,count(distinct UserIPAddress) as TotalHits
   -> from UniqueCountByIPAddress group by UserHits;

以下是输出 −

+----------+-----------+
| UserHits | TotalHits |
+----------+-----------+
|       10 |         1 |
|       20 |         2 |
|       30 |         1 |
+----------+-----------+
3 rows in set (0.05 sec)

相关文章