select 的使用
- 查询表内所有属性名的属性值
select * from table 表名;
- 查询表内指定属性名的属性值
select 属性名1,属性名2... from table 表名;
where 表达式
符号 | 表达式 | 功能 |
---|
= | 属性名 = 属性值 | 判断是否相等 |
!= \ <> | 属性名 != 属性值 \ 属性值 <> 属性值 | 判断是否不相等 |
>= \ > \ <= \ < | | 判断大小关系 |
between… and… | 属性名 between 值1 and 值2 | 在范围内 |
not between… and… | 属性名 not between 值1 and 值2 | 不在范围内 |
in | 属性名 in (值1, 值2 …) | 查找多个匹配的数值 |
like | 属性名 like ‘%匹配字符串%’ | 模糊查询 %表示占位字符 |
and | 表达式1 and 表达式2 | 逻辑与 |
or | 表达式1 or 表达式2 | 逻辑或 |
is (not) null | 属性名 is (not) null | 判断是否(不)为空 |
创建学生表并插入数据
create table student_tb(
stu_id int primary key,
stu_name varchar(20),
grade int
);
insert into student_tb values
(1,'学生A',80),
(2,'学生B',90),
(3,'学生C',95),
(4,'学生D',65),
(5,'学生E',50),
(6,'学生F',50),
(7,'学生G',90),
(8,'学生G',80);
- 查询所有数据
select * from student_tb;
- 查询指定属性名的数据
select stu_name from student_tb;
- 根据属性值大小关系查询
select * from student_tb where grade>60;
- (not) between and 语句
select * from student_tb where grade between 70 and 90;
select * from student_tb where grade not between 70 and 90;
- in 语句
select * from student_tb where grade in(80,90);
- like 模糊查询
select * from student_tb where stu_name like '%学生%';
- and \ or 多条件查询
select * from student_tb where grade < 90 and grade > 60;
select * from student_tb where grade > 80 or grade < 60;
- is (not) null 语句
select * from student_tb where stu_name is not null;
去重查询 distinct
select distinct 属性名 from 表名;
select distinct stu_name from student_tb;
分页查询 limit
查询语句 limit [offset,]rows;
offset 默认为 0 查询从 offset 开始的 rows 个数据
select * from student_tb limit 3; 查询前三条数据
select * from student_tb limit 0,3; 同上一条语句
select * from student_tb limit 3,5; 查询第三条数据及后面四个数据
创建表时复制其他表的数据
create table 表名(select 语句);
create table student2_tb(select * from student_tb);
可以复制其他表的属性与数据,但是无法复制主键,因此创建的是无主键的表
排序 order by
select * from 表名 order by 属性名 [desc];
desc 表示降序 不加默认升序
select * from student_tb order by grade;
select * from student_tb order by grade desc;