按另一个 MySQL 表中的列进行分组
mysqlmysqli database
为此,您可以使用 CREATE TABLE AS SELECT 语句。让我们首先创建一个表 −
mysql> create table DemoTable1 -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> CountryName varchar(20) -> ); Query OK, 0 rows affected (0.68 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable1(CountryName) values('US'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable1(CountryName) values('UK'); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable1(CountryName) values('AUS'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable1(CountryName) values('UK'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1(CountryName) values('UK'); Query OK, 1 row affected (0.06 sec) mysql> insert into DemoTable1(CountryName) values('US'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable1(CountryName) values('AUS'); Query OK, 1 row affected (0.10 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable1;
输出
+----+-------------+ | Id | CountryName | +----+-------------+ | 1 | US | | 2 | UK | | 3 | AUS | | 4 | UK | | 5 | UK | | 6 | US | | 7 | AUS | +----+-------------+ 7 rows in set (0.00 sec)
以下是对另一个表中的列进行 GROUP BY 的查询−
mysql> create table DemoTable2 AS select *from DemoTable group by CountryName; Query OK, 3 rows affected (0.79 sec) Records: 3 Duplicates: 0 Warnings: 0
现在检查新表中的记录 −
mysql> select *from DemoTable2;
输出
+----+-------------+ | Id | CountryName | +----+-------------+ | 1 | US | | 2 | UK | | 3 | AUS | +----+-------------+ 3 rows in set (0.00 sec)