在 MySQL 中使用 GROUP BY 获取行?
让我们先创建一张表 -
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Subject varchar(20), Price int ); Query OK, 0 rows affected (0.64 sec)
使用 insert 命令向表中插入一些记录 -
mysql> insert into DemoTable(Subject,Price) values('MySQL',456); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(Subject,Price) values('MySQL',456); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(Subject,Price) values('MongoDB',56); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(Subject,Price) values('MongoDB',60); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(Subject,Price) values('Java',100); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable(Subject,Price) values('Java',130); Query OK, 1 row affected (0.15 sec)
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable;
输出
+----+---------+-------+ | Id | Subject | Price | +----+---------+-------+ | 1 | MySQL | 456 | | 2 | MySQL | 456 | | 3 | MongoDB | 56 | | 4 | MongoDB | 60 | | 5 | Java | 100 | | 6 | Java | 130 | +----+---------+-------+ 6 rows in set (0.00 sec)
以下是在 MySQL 中使用 GROUB BY 获取行的查询 -
mysql> select sum(Price) AS Total, Subject from DemoTable group by Subject;
输出
+-------+---------+ | Total | Subject | +-------+---------+ | 912 | MySQL | | 116 | MongoDB | | 230 | Java | +-------+---------+ 3 rows in set (0.04 sec)
广告