我们已经知道了通过select 查询记录、通过update 更新记录、通过delete删除记录,通过where子句限制条件。我们来讲一些高级的用法。
合并多个查询
有两条sql查询:select id,name from user_tb
、select id,u_name from client_tb
;现在我发现其实这两条查询可以合并:name 和 u_name
只是命名不同,本质意义是一样地,那么我们就可以合并这两条查询:distinct 和 all 表示删除or保留重复地记录(默认distinct删除).必须保证合并的每个select查询的列的个数相同
select id,name from user_tb union select id,u_name from client_tb;
select id,name from user_tb union all select id ,u_name from client_tb;
模糊查询
有的时候,需要根据字符匹配表记录:比如查询关联字符good
的字段character
。这就用要like
- 字符为开头:
where character like 'good%'
- 字符为结尾:
where character like '%good'
- 包含该字符,无论开头还是结尾:
where character like '%good%'
对查询结果集排序
- 排序字段
order by column_name
- 升
asc
or降序desc
select * from user_tb order by name desc
连接
现在我们需要某个集合,该集合是由多张表里的信息组成的,此时我们就要用到连接。
现在有两张表,需要以name为对比,拼凑
id | name | sex |
---|---|---|
1 | 张三 | 男 |
2 | 李四 | 男 |
3 | 小花 | 女 |
id | name | age |
---|---|---|
1 | 张三 | 12 |
3 | 小花 | 15 |
inner join(交集)
select a.id, a.name, a.sex, b.age from table_1 a INNER JOIN table_2 b ON a.name = b.name;
结果为:
id | name | sex | age |
---|---|---|---|
1 | 张三 | 男 | 12 |
3 | 小花 | 女 | 15 |
left join(以左侧为base的并集)
select a.id, a.name, a.sex, b.age from table_1 a LEFT JOIN table_2 b ON a.name = b.name;
结果为:
id | name | sex | age |
---|---|---|---|
1 | 张三 | 男 | 12 |
2 | 李四 | 男 | null |
3 | 小花 | 女 | 15 |
right join(以右侧为base的并集)
…与left join 类似
分组
有的场景需要将一部分记录抽象为一个组,比如name为'张三'的row
,base为上海的与会者们
…,然后针对该组做统计(平均值avg、记录的count、最大值max、最小值min...
)
- 代表统计操作的
函数名
+字段名 group by
+字段名
SELECT name, avg(score)
FROM user_table
GROUP BY name;
以上代码表示 以name字段为分组条件,统计每一组得分的平均值。
null的处理
现在我们想查询 user_table表里name为null的记录,怎么做?select * from user_table where name = null
是不行的。应该用 is null
、 is not null
表示空、非空。
select * from user_table where name is null;