- DQL:Data Query Language
- 作用:查询结果,返回结果集。
- 常用关键字: SELECT
- 基本SELECT语句
SELECT [DISTINCT] *|{column1,column2,column3...} FROM table;
SELECT *|{column1,column2...|expression...} FROM table;
SELECT column1,column2,column3... FROM table ORDER BY column asc\desc;(升序\降序,默认升序)
实践操作
- 查询表中所有学生的信息。
SELECT * FROM student;
- 查询表中所有学生的姓名和对应的英语成绩。
SELECT name,english FROM student;
- 过滤表中重复数据。
SELECT DISTINCT english FROM student;
(DISTINCT用于显示结果时,是否剔除重复数据)
- 在所有学生数学分数上加10分特长分。
SELECT name,math + 10 FROM student;
- 统计每个学生的总分。
SELECT name,(chinese + english + math) FROM student;
- 使用别名表示学生分数。
SELECT name AS 姓名,(chinese + english + math) 总分 FROM student;
(AS可省略,别名)
- 查询姓名为王五的学生成绩
SELECT * FROM student WHERE name = '王五';
- 查询英语成绩大于90分的同学
SELECT * FROM student WHERE english > 90;
-查询总分大于200分的所有同学
SELECT * FROM student WHERE (chinese + english + math) > 200;
- 查询英语分数在80-90之间的同学
SELECT * FROM student WHERE english BETWEEN 80 AND 90;
- 查询数学分数为89,90,91的同学
SELECT * FROM student WHERE math IN(89,90,91);
- 查询所有姓李的学生成绩
SELECT * FROM student WHERE name LIKE '李%';
- 查询数学分>80,语文分>80的同
SELECT * FROM student WHERE chinese > 80 AND math > 80;
- 对数学成绩排序后输出
SELECT name,math FROM student ORDER BY math ASC;
- 对总分排序后输出,然后再按从高到低的顺序输出
SELECT *,(chinese + english + math) AS 总分 FROM student ORDER BY (chinese + english + math) DESC;
- 对姓李的学生成绩排序输出
SELECT * FROM student WHERE name LIKE '李%' ORDER BY (chinese + english + math);
多表查询(此部分属于更新内容,下面的数据库都是在此文集《数据完整性》章节里面建好的)
- 链接查询:(面试几率很大)
a、交叉连接:
SELECT * FROM customers,orders;
返回的是两张表的笛卡儿积。(隐式查询,不使用关键字)
或者
SELECT * FROM customers CROSS JOIN orders;
b、内连接:
SELECT * FROM customers AS c,orders o WHERE c.id = o.customer_id;
或者
SELECT * FROM customers AS c INNER JOIN orders o ON c.id = o.customer_id;
c、外连接:
- 查询所有的客户信息,同时把对应的订单查询出来。
左外:返回符合链接条件的记录,同时返回左表中不满足链接条件的剩余记录
SELECT * FROM customers AS c LEFT OUTER JOIN orders o ON c.id = o.customer_id;
右外:SELECT * FROM customers AS c LEFT OUTER JOIN orders o ON c.id = o.customer_id;
- 几个简单的子查询
- 嵌套查询:子查询的语句放到小括号内部。
id = 1这个老师教过哪些学员(语句的查询形式:多条SQL语句)
SELECT s_id FROM teacher_student WHERE t_id = 1;
SELECT * FROM students WHERE id IN (1,2);
子查询:
SELECT * FROM students WHERE id IN (SELECT s_id FROM teacher_student WHERE t_id = 1);