SQL语句 笔记

column 列 row 行

Structured Query Language结构化查询语言 relationship database


Select 字段1, 字段2, 字段3 from 表名 where 字段 条件

Select * from table where 1; *代表所有, where 1表示没有条件。


一、数字条件查询(where)

Select * from table where 字段 = 1;

OperatorSQL Example解释
!=, < <=, > >=,字段 != 4等于, 大于,小于
between...and...字段 between 1.5 and 2在1.5和2之间
not between...and...字段 not between 1.5 and 2不在1.5和2之间
in (...)字段 in (2, 4, 6)在集合里
not in (...)字段 not in (2, 4, 6)不在集合里

二、文本字符串查询(where)

Select * from table where 字段 like ‘%abc’;

OperatorSQL Example解释
=字段 = “abc”等于
!= or <>字段 != “abc”不等于
like字段 like “abc”等于
not like字段 not like “abc”不等于
%字段 like “%at%”前中后均匹配模糊匹配
_字段 like “an_”只匹配后,不匹配本身模糊匹配单字符
in (...)字段 in (a, b, c)在集合里
not in (...)字段 not in (a, b, c)不在集合里

三、查询结果Filtering过滤和sorting排序

Select Distinct 字段1, 字段2 from table where conditions order by 字段 asc limit 2 offset 2;

OperatorSQL Example解释
order byorder by 字段1按字段排序
ascorder by 字段1 asc升序
descorder by 字段1 desc降序
limit offsetlimit num_limit  offset num_offset从offset取limit
order byorder by 字段1 asc, 字段2 desc多列排序

四、多表连接查询

Select * from table1 left join table2 on table1.id = table2.id where 字段 > 1

OperatorSQL Example解释
join...on...t1 join t2 on t1.id = t2.id按ID连成一个表
inner joint1 inner join t2 on t1.id = t2.id只保留id相等的row
left joint1 left join t2 on t1.id = t2.id保留t1的所有row
right joint1 right join t2 on t1.id = t2.id保留t2的所有row
is/is not null字段 is/is not null字段是不是为null空

五、表达式查询

1. Select particle_speed / 2.0 as half_particle_speed (对u结果做了除以2的运算)

from physics_data where ABS(particle_position) * 1.0 > 500;(条件要求这个属性的绝对值乘以10大于500)

2. Select *, 字段*2 from table where 字段/2 > 1;

OperatorSQL Example解释
+ - * / %字段1 + 字段2字段之间的加减乘除
substrsubstr(字段, 0, 4)字符串截取
as字段 * 2 as 新字段名字段取别名

每一种数据库都有自己的一套函数(eg: mysql, sqlserver),包含常用数字、字符串、时间等处理过程,具体的参考对应数据库规则。

As 作为使用别名

Select Description as D, 

六、查询统计

SQL默认支持一组统计表达式,可以进行数据统计,例如:计数,求均值,求和,查询极值。

Select AGG_FUNC(column_or_expression) as aggregate_description, ...

from table where constraint_expression; 

在这里必须指明如何分组,否则统计函数对查询结果全部数据进行统计。也可以通过as取别名来增强可读性。

Select count(*), avg(字段), 字段 from table where 字段 > 1 group by 字段; 

OperatorSQL Example解释

count(*)

count(字段)

count(*)

count(字段, 字段)

计数
min(字段)min(字段)最小值
max(字段)max(字段)最大值
avg(字段)avg(字段)求平均
sum(字段)sum(字段)求和
group bygroup by字段1, 字段2分组
havinghaving 字段 > 100分组后条件

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值