如何仅从一个 MySQL 列中选择不同值?
仅要从一个列中选择不同值,你可以使用聚合函数 MAX() 以及 GROUP BY。我们先创建一个表 −
mysql> create table distinctFromOneColumn -> ( -> StudentId int, -> StudentName varchar(100) -> ); Query OK, 0 rows affected (0.77 sec)
以下是使用 insert 命令在表中插入记录的查询 −
mysql> insert into distinctFromOneColumn values(1001,'John'); Query OK, 1 row affected (0.15 sec) mysql> insert into distinctFromOneColumn values(1002,'Carol'); Query OK, 1 row affected (0.15 sec) mysql> insert into distinctFromOneColumn values(1001,'Sam'); Query OK, 1 row affected (0.15 sec) mysql> insert into distinctFromOneColumn values(1001,'David'); Query OK, 1 row affected (0.16 sec) mysql> insert into distinctFromOneColumn values(1002,'Ramit'); Query OK, 1 row affected (0.15 sec) mysql> insert into distinctFromOneColumn values(1003,'Bob'); Query OK, 1 row affected (0.21 sec)
以下是使用 select 语句显示表中所有记录的查询 −
mysql> select * from distinctFromOneColumn;
这将产生以下输出 −
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 1001 | John | | 1002 | Carol | | 1001 | Sam | | 1001 | David | | 1002 | Ramit | | 1003 | Bob | +-----------+-------------+ 6 rows in set (0.00 sec)
以下是仅从一个列中选择不同值的查询 −
mysql> select StudentId,MAX(StudentName) AS StudentName -> from distinctFromOneColumn -> group by StudentId;
这将产生以下输出 −
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 1001 | Sam | | 1002 | Ramit | | 1003 | Bob | +-----------+-------------+ 3 rows in set (0.00 sec)
广告