Mysql基础(二)

我们已经知道了通过select 查询记录、通过update 更新记录、通过delete删除记录,通过where子句限制条件。我们来讲一些高级的用法。

合并多个查询

有两条sql查询:select id,name from user_tbselect id,u_name from client_tb;现在我发现其实这两条查询可以合并:name 和 u_name只是命名不同,本质意义是一样地,那么我们就可以合并这两条查询:distinctall 表示删除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
  • ascor降序desc
select * from user_tb order by name desc

连接

现在我们需要某个集合,该集合是由多张表里的信息组成的,此时我们就要用到连接。
现在有两张表,需要以name为对比,拼凑

idnamesex
1张三
2李四
3小花
idnameage
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;

结果为:

idnamesexage
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;

结果为:

idnamesexage
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 nullis not null表示空、非空。

select * from user_table where name is null;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值