如何仅从一列中选择不同的值?
mysqlmysqli database更新于 2023/12/18 20:21:00
要仅从一列中选择不同的值,可以使用聚合函数 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)