当前位置: 首页 > 教程 > MariaDB >

MariaDB查询数据

精华
小牛编辑
120浏览
2023-03-14

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以升序排列行记录。