Computer >> 컴퓨터 >  >> 프로그램 작성 >> MySQL

ORDER BY 절을 사용하여 MySQL 보기를 어떻게 생성할 수 있습니까?


MySQL ORDER BY 절을 사용하여 결과 집합의 레코드를 정렬할 수 있습니다. . 뷰가 있는 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 ORDER BY expression [ASC|DESC]

예시

mysql> Create or Replace View Info AS select ID, Name, Address , Subject FROM Student_info ORDER BY Name ASC;
Query OK, 0 rows affected (0.11 sec)

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

mysql> Create or Replace View Info AS select ID, Name, Address , Subject FROM Student_info ORDER BY Name DESC;
Query OK, 0 rows affected (0.10 sec)

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