本文共 3059 字,大约阅读时间需要 10 分钟。
在学习SQL时,熟悉基本语法是立足的基础。以下是SQL语句的几种基本操作和技巧。
where子句用于对数据库中的数据进行筛选,只有满足条件的行会出现在结果集中。
在显示查询结果时,字段名可能不够友好或难以理解。此时可以使用as关键字为字段起一个更具可读性的别名。
select id as 序号, name as 名字, gender as 性别 from students;
-- 单表查询可省略表名select id, name, gender from students;-- 使用as为表起别名select s.id, s.name, s.gender from students as s;
如果需要去重,可以使用distinct关键字。
select distinct gender from students;
select * from 表名 where 条件;
select * from students where id=1;
where子句支持多种运算符,包括比较运算符、逻辑运算符、模糊查询、范围查询和空判断等。
常用的比较运算符包括:
=
>
>=
<
<=
!=
select * from students where is_delete=0;
支持的逻辑运算符包括AND、OR、NOT。
select * from students where not id > 3 and gender=0;
模糊查询可以匹配部分数据,常用的关键字包括LIKE和RLIKE。
%
表示任意多个任意字符_
表示一个任意字符select * from students where name like '黄%' or name like '%靖';
支持正则表达式匹配。
select * from students where name rlike '^周.*伦$';
范围查询可以分为两种类型:IN和BETWEEN。
用于非连续范围查询。
select * from students where id in (1,3,8);
用于连续范围查询。
select * from students where id between 3 and 8;
使用is null
判断字段是否为空。
select * from students where height is null;
查询优先级由高到低依次为:小括号、NOT、比较运算符、逻辑运算符。
select * from students where not (id > 3 and gender=0);
select * from 表名 order by 列1 asc|desc [,列2 asc|desc,...];
asc
表示升序(默认)desc
表示降序select * from students order by age desc, height desc;
sum(max(xx))
)常用的聚合函数包括:
count(*)
:计算总行数max()
:求最大值min()
:求最小值sum()
:求和avg()
:求平均值select round(avg(age),2) from students where is_delete=0 and gender=2;
group by
用于根据指定字段对数据进行分组。select gender from students group by gender;
用于将同一分组内的字段值拼接成一个字符串。
select gender, group_concat(name) from students group by gender;
可以使用聚合函数对每个分组进行统计。
select gender, avg(age) from students group by gender;
用于对分组结果进行过滤。
select gender, count(*) from students group by gender having count(*)>2;
用于在分组结果末尾添加汇总行。
select gender, group_concat(age) from students group by gender with rollup;
select * from 表名 limit [offset,]rowcount;
offset
表示起始位置,默认为0rowcount
表示要取的行数select * from students where gender=1 limit 0,3;
((总条数 - 1) / 每页大小) + 1
select * from 表名 limit ((页码-1)*每页大小, 每页大小)
select * from students where is_delete=0 limit (n-1)*m, m;
select * from 表1 inner join 表2 on 表1.字段=表2.字段;
select * from 表1 left join 表2 on 表1.字段=表2.字段;
select * from 表1 right join 表2 on 表1.字段=表2.字段;
select s.cls_id, s.*, c.name from students as s left join classes as c on s.cls_id=c.id order by cls_id;
用于同一表进行多次关联。
select city.* from areas as city inner join areas as province on city.pid=province.aid where province.atitle='山西省';
嵌入子查询用于辅助主查询的条件判断或数据获取。
select s.name, count(*) as 该名的总数 from students as s where s.id in (select id from students where is_delete=0);
通过以上内容,可以逐步掌握SQL的基本语法和使用场景。
转载地址:http://sjdfk.baihongyu.com/