For this, you can use CREATE TABLE AS SELECT statement. Let us first create a table −
mysql> create table DemoTable1 -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> CountryName varchar(20) -> ); Query OK, 0 rows affected (0.68 sec)
Insert some records in the table using insert command −
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)
Display all records from the table using select statement −
mysql> select *from DemoTable1;
Output
+----+-------------+ | Id | CountryName | +----+-------------+ | 1 | US | | 2 | UK | | 3 | AUS | | 4 | UK | | 5 | UK | | 6 | US | | 7 | AUS | +----+-------------+ 7 rows in set (0.00 sec)
Following is the query to GROUP BY a column in another table −
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
Now check the records in the new table −
mysql> select *from DemoTable2;
Output
+----+-------------+ | Id | CountryName | +----+-------------+ | 1 | US | | 2 | UK | | 3 | AUS | +----+-------------+ 3 rows in set (0.00 sec)