如何用 GROUP BY 子句创建一个 MySQL 视图?


我们可以使用 GROUP BY 对某一列的值分组,而且如果需要的话,我们可以对该列执行计算。你可以在分组的列上使用 COUNT、SUM、AVG 等函数。为了了解使用视图的 GROUP BY 子句,我们要使用具有以下数据的基本表 ‘Student_info’ 创建一个名为 ‘Info’ 的视图 −

mysql> Select * from Student_info;
+------+---------+------------+------------+
| id   | Name    | Address    | Subject    |
+------+---------+------------+------------+
| 101  | YashPal | Amritsar   | History    |
| 105  | Gaurav  | Chandigarh | Literature |
| 125  | Raman   | Shimla     | Computers  |
| 130  | Ram     | Jhansi     | Computers  |
| 132  | Shyam   | Chandigarh | Economics  |
| 133  | Mohan   | Delhi      | Computers  |
+------+---------+------------+------------+
6 rows in set (0.00 sec)

语法

Create or Replace View view_name AS Select_statements FROM table GROUP BY expression1, expression2, ... expression_n;

示例

mysql> Create or Replace View Info AS select Subject, COUNT(*) FROM Student_info GROUP BY Subject;
Query OK, 0 rows affected (0.10 sec)

mysql> Select * from info;
+------------+----------+
| Subject    | COUNT(*) |
+------------+----------+
| Computers  |    3     |
| Economics  |    1     |
| History    |    1     |
| Literature |    1     |
+------------+----------+
4 rows in set (0.00 sec)

mysql> Create or Replace View Info AS select Subject,Name, COUNT(Subject) FROM Student_info GROUP BY Subject, Name;
Query OK, 0 rows affected (0.05 sec)

上述查询将在 GROUP BY 子句中有两列。

mysql> Select * from info;
+------------+---------+----------------+
| Subject    | Name    | COUNT(Subject) |
+------------+---------+----------------+
| Computers  | Mohan   |       1        |
| Computers  | Ram     |       1        |
| Computers  | Raman   |       1        |
| Economics  | Shyam   |       1        |
| History    | YashPal |       1        |
| Literature | Gaurav  |       1        |
+------------+---------+----------------+
6 rows in set (0.00 sec)

上述结果集表明,GROUP BY 子句按照列的值,将一组行分组为一组汇总行。

更新于:30-Jul-2019

2K+ 浏览

开启你的 职业 生涯

通过完成本课程获得认证

开始
广告