按另一张 MySQL 表中的一列分组


为此,你可以使用 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)

以下是按另一张表中的一列分组的查询 −

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)

上次更新时间: 2019-07-30

245 次浏览

开启你的 事业

完成该课程并获得认证

开始
广告