首頁 >資料庫 >mysql教程 >我們如何使用 GROUP BY 子句建立 MySQL 視圖?

我們如何使用 GROUP BY 子句建立 MySQL 視圖?

WBOY
WBOY轉載
2023-09-02 12:49:021486瀏覽

我们如何使用 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 子句會以列的值將一組行分組為一組總計行。

以上是我們如何使用 GROUP BY 子句建立 MySQL 視圖?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除