SELECT
語(yǔ)句用于從單個(gè)或多個(gè)表中檢索記錄。
語(yǔ)法
SELECT expressions
FROM tables
[WHERE conditions];
SELECT
語(yǔ)句可以與UNION
語(yǔ)句,ORDER BY
子句,LIMIT
子句,WHERE
子句,GROUP BY
子句,HAVING
子句等一起使用。如下語(yǔ)法 -
SELECT [ ALL | DISTINCT ]
expressions
FROM tables
[WHERE conditions]
[GROUP BY expressions]
[HAVING condition]
[ORDER BY expression [ ASC | DESC ]];
示例:
我們有一個(gè)表students
,有一些數(shù)據(jù)。 因此,從students
中檢索所有記錄。參考以下查詢語(yǔ)句 -
SELECT * FROM students;
執(zhí)行上面查詢語(yǔ)句,得到以下結(jié)果 -
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)
可以使用SELECT
語(yǔ)句從表中檢索單個(gè)列(指定列)。它有助于您只檢索那些需要的列。
示例:
SELECT student_id, student_name, student_address
FROM Students
WHERE student_id < 4
ORDER BY student_id ASC;
執(zhí)行上面查詢語(yǔ)句,得到以下結(jié)果 -
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)
在上面查詢語(yǔ)句中,它查詢表student
中那些student_id
小于4
,并選擇student_id
,student_name
,student_address
列,然后根據(jù)student_id
以升序排列行記錄。