文档首页
MySQL Shell for VS Code


MySQL Shell for VS Code  /  SQL  /  使用 SELECT 语句检索数据

预发布:2024-07-17

6.2 使用 SELECT 语句检索数据

从 sakila.actor 中选择 ID、姓和名

SELECT actor_id as ID, first_name as 'First Name', last_name as 'Last Name' from sakila.actor;

输出为

+-----+-------------+--------------+
| ID  | First Name  | Last Name    |
+-----+-------------+--------------+
|   1 | PENELOPE    | GUINESS      |
|   2 | NICK        | WAHLBERG     |
|   3 | ED          | CHASE        |
|   4 | JENNIFER    | DAVIS        |

...

| 198 | MARY        | KEITEL       |
| 199 | JULIA       | FAWCETT      |
| 200 | THORA       | TEMPLE       |
+-----+-------------+--------------+
OK, 200 records retrieved in (0.0028 sec)
 

使用 WHERE 从 sakila.actor 中选择 ID、姓和名

SELECT actor_id, first_name, last_name FROM sakila.actor WHERE first_name LIKE 'Cate';

输出为

+----------+------------+-----------+
| actor_id | first_name | last_name |
+----------+------------+-----------+
|      128 | CATE       | MCQUEEN   |
|      141 | CATE       | HARRIS    |
+----------+------------+-----------+
OK, 2 records retrieved in 0.991ms

使用 WHERE 和通配符从 sakila.actor 中选择 ID、姓和名

SELECT actor_id, first_name, last_name FROM sakila.actor WHERE last_name like '%han%';

输出为

+----------+------------+-----------+
| actor_id | first_name | last_name |
+----------+------------+-----------+
|        8 | MATTHEW    | JOHANSSON |
|       64 | RAY        | JOHANSSON |
|      146 | ALBERT     | JOHANSSON |
+----------+------------+-----------+      
OK, 3 records retrieved in 0.996ms

选择 sakila.film 中评级的计数,并按评级分组

SELECT rating AS label, count(rating) AS value FROM sakila.film GROUP BY rating;

输出为

+--------+-------+
| Rating | Count |
+--------+-------+
| PG     |   194 |
| G      |   178 |
| NC-17  |   210 |
| PG-13  |   223 |
| R      |   195 |
+--------+-------+
OK, 5 records retrieved in 1.905ms

从 sakila.language 和 sakila.film 中选择语言和语言计数

SELECT l.name AS Language, count(f.film_id) AS Count FROM sakila.language l, 
sakila.film f WHERE f.language_id = l.language_id 
GROUP BY f.language_id ORDER BY COUNT DESC;

输出为

+----------+-------+
| Language | Count |
+----------+-------+
| English  |   439 |
| German   |   246 |
| Italian  |   124 |
| Japanese |    96 |
| Mandarin |    76 |
| French   |    19 |
+----------+-------+
OK, 6 records retrieved in 1.425ms