day04_mysql:数据查询详解

select xxx from x1 join x2 on x1.x = x2.x

where xxxx

group by xxxx

having xxxx

order by xxxx

limit n;

 

1. 条件查询

1. 1 单条件查询

where 运算操作符:=   <>   !=   <   <=   >   >=   BETWEEN  IN

where 组合操作符:AND OR NOT;其中 AND 优先级高于 OR,为避免优先级混淆,最好加圆括号提升优先级运算。NOT一般用于(IN、BETWEEN、EXISTS子句取反)

where 中 LIKE 操作符、%和_通配符:%表示任何字符出现任意次数。_表示任意单个字符。

where 中 REGEXP 正则操作符。

注:查询时尽量避免使用 LIKE 和 REGEXP,会降低检索速度。

where 数值字段 >=value1;

where 字段 in (value1, value2, ...);

where 字段 not in (value1, value2, ...);

where 字段 between value1 and value2;

where 字段 not between value1 and value2;

where 字段 is null;

where 字段 like 'a%';

where 字段 like '%a';

where 字段 like '%a%';

where 字段 like '__a';   # _ 表示占位符,一个_表示一个字符

1.2 多条件查询

and  or  and优先级高于or,可用括号来优先计算

 

2. 分组查询

2.1 简单分组查询

group by  group by 关键字通常和聚合函数一起使用

常见聚合函数有count() 按分组计数, group_concat()按分组拼接字符串

isnull() 判断是否为空,常用于替换空值,第二个参数传入要替换的值

avg()返回某列的均值

max()返回最大值

min() 返回最小值

count() 计数

sum() 求和

 

2.2 分组查询结果-再过滤/筛选

group by 字段 having 条件语句 

group by 字段后 加 with rollup 会对记录进行汇总统计

where 中的条件判断和having中的一样,where 是在分组前过滤,having 是在分组后过滤

3. 记录排序

order by 字段1, 字段2,...  desc 关键字表示降序

4. 查询记录返回数量限制/偏移

limit 

limit n;  限制返回n个;

limit n, m;  限制返回第n个到第m个;

limit 实现分页算法 (page-1) * pageSize

5. case when 语句  对每条记录进行划分类别

select position,

case

  when position>10 then 'high'

  when position>5 then 'mid'

  else 'low'

end as 'position_category'

from table1;

 

6. 建立索引 ——加快查询速度,不要增加太多索引,会降低写速度。

create index index_name on table1(id);

show index from table1;

drop index index_name on table1;

7. 多表联结查询

inter join

left join

right join

from table1 join  table2 on table1.id = table2.t1_id

8. 正则表达式查询

9. 计算字段:Concat()函数、加减乘除(+ - * / )

文本处理函数:Left()   Length()   Locate()   Lower()   Right()  Trim() / RTrim() / LTrim()  Soundex() SubString()   Upper()

select concat(a,'  (', b, ')') from x1 order by name;

日期和时间处理函数:Date()   Time() Month() Year() ...

数值处理函数:Abs() Cos()  Sin()  Tan()  Mod() Sqrt()  Rand()  PI()  

10. 子查询

转载于:https://www.cnblogs.com/cooqes/p/10409140.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值