在前一篇中最后对部分对数据表进行了简单对查询操作,但在实际应用中,很大一部分工作都是在对数据库进行查询操作,即对数据表记录的查询。
环境
PyCharm Professional 2018.3.1 + MySQL Community 8.0.15
创建一张表
打开MySQL服务后,进入数据库,创建表 “exam_result” :
-- 创建表
CREATE TABLE exam_result(
id INT PRIMARY KEY AUTO_INCREMENT, -- 主键
name VARCHAR(20), -- 姓名
JS DOUBLE, -- JS 成绩
Django DOUBLE, -- Django 成绩
Python DOUBLE -- Python 成绩
);
-- 插入表记录
INSERT INTO exam_result VALUES (1,"Alia",87,78,91),
(2,"John",75,83,96),
(3,"Downey",98,91,87),
(4,"Lee",99,83,95),
(5,"Manda",71,65,80),
(6,"Karla",61,59,100);
查看所有表记录——SELECT * FROM tab_name;
SELECT * FROM exam_result;
查看表记录中的一列——SELECT col_name FROM tab_name;
SELECT name FROM exam_result;
DISTICT关键字——去除重复,保留不同
在表记录中,可能会包含重复值,有时我们希望仅仅列出不同的值,就需要使用 DISTICT关键词。
首先我在 “exam_result” 中添加几个重复值:
INSERT INTO exam_result VALUES (7,"Alia",72,94,86),
(8,"Alia",71,94,53),
(9,"Lee",100,94,95);
SELECT * FROM exam_result;
SELECT DISTINCT name FROM exam_result;
AS 关键字——更改字段名
在显示时使用 “AS" 关键字可以更改字段名,可以省略,使用空格替代(建议保留AS关键字)。
注意: “AS” 关键字仅仅更改显示内容,不会改变数据表对内容。
SELECT name AS 姓名, JS JS成绩, Python+10 AS Python成绩 FROM exam_result;
WHERE字句——进行过滤查询
“WHERE” 字句可以对查询信息进行过滤,字句中可以使用:
SELECT name,JS FROM exam_result WHERE JS BETWEEN 75 AND 95;
SELECT name,JS FROM exam_result WHERE JS IN (71,85,90);
SELECT name,JS FROM exam_result WHERE name LIKE 'A%';
SELECT name,JS FROM exam_result WHERE name LIKE 'Le_';
SELECT name,JS,Django FROM exam_result WHERE JS >80 AND Django != 100;
SELECT name,JS,Django FROM exam_result WHERE JS >80 ORDER BY Django;
SELECT name,JS,Django FROM exam_result WHERE JS >80 ORDER BY Django DESC;
SELECT name,JS+Django+Python as 总成绩 FROM exam_result ORDER BY 总成绩;
SELECT * FROM exam_result GROUP BY name;
进行查询时,会出现这样的报错:注: