MariaDB查詢資料


SELECT語句用於從單個或多個表中檢索記錄。

語法

SELECT expressions  
FROM tables  
[WHERE conditions];

SELECT語句可以與UNION語句,ORDER BY子句,LIMIT子句,WHERE子句,GROUP BY子句,HAVING子句等一起使用。如下語法 -

SELECT [ ALL | DISTINCT ]  
expressions  
FROM tables  
[WHERE conditions]  
[GROUP BY expressions]  
[HAVING condition]  
[ORDER BY expression [ ASC | DESC ]];

1. 從表中選擇所有列

範例:

我們有一個表students,有一些資料。 因此,從students中檢索所有記錄。參考以下查詢語句 -

SELECT * FROM students;

執行上面查詢語句,得到以下結果 -

MariaDB [testdb]> SELECT * FROM Students;
+------------+--------------+-----------------+----------------+
| student_id | student_name | student_address | admission_date |
+------------+--------------+-----------------+----------------+
|          1 | Maxsu        | Haikou          | 2017-01-07     |
|          3 | JMaster      | Beijing         | 2016-05-07     |
|          4 | Mahesh       | Guangzhou       | 2016-06-07     |
|          5 | Kobe         | Shanghai        | 2016-02-07     |
|          6 | Blaba        | Shengzheng      | 2016-08-07     |
+------------+--------------+-----------------+----------------+
5 rows in set (0.00 sec)

2. 從表中選擇指定列

可以使用SELECT語句從表中檢索單個列(指定列)。它有助於您只檢索那些需要的列。

範例:

SELECT student_id, student_name, student_address  
FROM Students  
WHERE student_id < 4  
ORDER BY student_id ASC;

執行上面查詢語句,得到以下結果 -

MariaDB [testdb]> SELECT student_id, student_name, student_address
    -> FROM Students
    -> WHERE student_id < 4
    -> ORDER BY student_id ASC;
+------------+--------------+-----------------+
| student_id | student_name | student_address |
+------------+--------------+-----------------+
|          1 | Maxsu        | Haikou          |
|          3 | JMaster      | Beijing         |
+------------+--------------+-----------------+
2 rows in set (0.18 sec)

在上面查詢語句中,它查詢表student中那些student_id小於4,並選擇student_idstudent_namestudent_address列,然後根據student_id以升序排列行記錄。