sql

126 阅读2分钟

sql

结构化查询语言,专门用来访问和处理数据库的语言,

-- 这是注释

查询

-- 从指定表中查询所有字段
select * from 表名;
​
-- 从指定表中查询指定字段
select 列名 from 表名;

插入

-- 列和值要一一对应
insert into 表名(列1、列2...) values(值1、值2...);

修改

-- 修改单个值
update 表名 set 列名 = 新的值 where 列名 = 某个值;
​
-- 修改多个值
update 表名 set 列名1 = 新的值1, 列名2 = 新的值2 where 列名 = 某个值;

删除

delete from 表名 where 列名 = 某个值;

where子句

用于限定选择的标准,在select、delete、update中都可以使用

select 列名 from 表名 where 列 运算符 值;
update 表名 set= 新值 where 列 运算符 值;
delete from 表名 where 列 运算符 值;
​
-- 运算符
-- = <>(不等于) > < >= <= between(在某个范围内) like(搜索某种模式)
-- ps: 某些版本的sql中<>也可以是!=

and和or运算符

and和or可在where子句中把两个或者多个条件连接起来

and表示必须同时满足多个条件,相当于js的&&

or表示只要满足一个条件即可,相当于js的||

-- e.g
-- 查询所有id小于三并且状态为0的用户
select * from users where id < 3 and status = 0;
-- 查询所有id小于三或者状态为0的用户
select * from users where id < 3 or status = 0;

排序

order by根据指定的列对结果集进行排序

默认升序(asc) 可以使用desc关键字进行降序排序

-- 单字段排序
-- 此两句等价 均为升序
select * from users order by status;
select * from users order by status asc;
-- 降序
select * from users order by status desc;
​
​
-- 多重排序 先按状态降序排序, 再按id升序排序
select * from users order by status desc, id asc;

count(*)

返回查询结果的总数据条数

select count(*) from 表名;

别名as

可以给查询出来的列设置别名

select count(*) as total from 表名;

image.png