这些常用 MySQL 用法,99% 的人都不知道!

本文首发于公众平台:腐烂的橘子

MySQL 对于后端程序员来讲是最熟悉不过了,不过 MySQL 有一些基本用法,99% 的人都不知道,考验技术基本功的时候到了,快来看看有没有你不知道的:

select

select 0,2,3,4; 会创建列名为 0,2,3,4 的数据,对应的数据也是 0,2,3,4。

比如下面的 SQL:

select 0,2,3,'4';

select 0,2,"3",'4';

注意对于 MySQL,使用别名使用单引号和双引号都可以。

not

在任何 where 条件中加入 not,表示与此条件相反。

select * from table where not(condition);

between

between a and b 表示 a <= 字段 <= b,字段类型可以是数字、字符串、日期。

select * from customers where birth_date between '1990-01-01' and '2000-01-01'

这里代表 1990-01-01 <= birth_date <= 2000-01-01

like

like ___y 代表匹配 三个字符+y 的数据,有几个下划线代表几个字符。

select * from customers where last_name like '_____y_';
select * from customers where bz_id like '5___8%';
  • 第 1 行可以匹配到 last_name 为 anddya11234ysdfasfaaaxxxxyy 的数据
  • 第 2 行代表 5xxx8xxxxxxx 这类的 bz_id

regexp

MySQL 除了可以用 like 匹配,还可以用正则。以下是最最常用的正则,掌握后可以应对 90% 以上的场景了:

  • ^ 开头
  • $ 结尾
  • | 逻辑或
  • [abcd] abcd 中的任意一个或多个
  • [a-f] 匹配 abcdef
select * from customers where last_name regexp '^field';
select * from customers where last_name regexp 'field$';
select * from customers where last_name regexp 'field$|mac';
select * from customers where last_name regexp '[032]a';
  • ^代表使用正则查询 last_name 以 field 开头的数据
  • $代表使用正则查询 last_name 以 field 结尾的数据
  • 代表使用正则查询 last_name 以 field 结尾或包含 mac 的数据
  • 代表使用正则查询 last_name 包含 a,且 a 的前面可能有 0 或 3 或 2

order by

在 MySQL 中,可以使用别名排序:

select id as 'nickname' from customers where biz_id regexp '[0a]4' order by nickname;

也可以使用列排序,如:

select first_name, last_name as 'xxxxx' from customers order by 1,2;

代表以第 1、2 列排序,由于排序是对查询到结果后进行的,所以以下 SQL 会报错,找不到第 2 列:

select first_name from customers order by 1,2;

不过以列排序保持 order by 1,2 不变,把 select first_name, last_name 改成 select store, first_name, second_name 后,会按 store, first_name 排序了,容易造成语义混乱,不是很推荐,索引尽量使用 order by first_name, last_name 这样语义明确的方式排序。

limit a,b 表示跳过 a 条记录,再查询 b 条记录

这是一个比较常用的语法了,不是 a 和 b 的含义也是比较容易混淆的。

比如有 3 页的数据,分别是:

  • page 1: 1-3
  • page 2: 4-6
  • page 3: 7-9

获取第 3 页的数据 7-9:

select * 
from customers
limit 6,3
  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

腐烂的橘子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值