天天看點

資料庫sql語句

作者:戰神七小姐姐

sql:增删改查。curd(c:增加,u:update修改,r:read查詢,d:delete删除)

查詢:表名和字段名加 ` 可以加快sql語句的查詢素的

  • select 字段,字段 from 表名
  • select `字段`,`字段` from `表名`
select username,password from oper_user // 查詢oper_user表裡的username和password字段
select `username`,`password` from `oper_user` // 查詢oper_user表裡的username和password字段
select * from oper_user // 查詢oper_user裡的所有字段

select * from `oper_user` where `id`=2 // 查詢oper_user中id為2的資料
select * from `oper_user` where `id`!=2 // 查詢oper_user中id不是2的資料
select * from `oper_user` where `id`<>2 // 查詢oper_user中id不等于2的資料
select * from `oper_user` where `id`>2 // 查詢oper_user中id大于2的資料
select * from `oper_user` where `id`<2 // 查詢oper_user中id小于2的資料
select * from `oper_user` where `id`>=2 // 查詢oper_user中id大于等于2的資料
select * from `oper_user` where `id`<=2 // 查詢oper_user中id小于等于2的資料

select * from `oper_user` where `id` in(1,3,4) // 查詢oper_user中id是1、id是3、id是4的資料
select * from `oper_user` where `id` not in(1,3,4) // 查詢oper_user中id不是1、id不是3,id不是4的資料
select * from `oper_user` where `id` between 2 and 4 // 查詢oper_user中id在2到4之間的資料(包括2和4)
select * from `oper_user` where `username`='admin' and `password`='admin123' // 查詢oper_user中username為admin并且password為admin123
select * from `oper_user` where `username`='admin' or `password`='admin123' // 查詢oper_user中username為admin或者password為admin123

select * from `oper_user` order by `create_time` asc // 按照create_time 升序
select * from `oper_user` order by `create_time` desc // 按照create_time降序
select * from `oper_user` where `id` in(1,3,4) order by `create_time` desc // 查詢id為1,3,4的降序資料
有where where必須要放在order by的前面

select * from `oper_user` where `id` between 4 and 20 limit 0,3 // 第1條開始查,查3條 
limit 起始位置,條數, 第1條資料的起始位置為0

select * from `oper_user` where `id` in(1,6,8,3) order by `id` asc limie 0,4 // id為1,6,8,3的資料根據id升序 第1條開始查,查4條
where在最前面,order by在中間 limit在最後,順序不能變

統計一張表中總共有多少資料
select count(*) from `oper_user` // 統計oper_user表中共有多少條資料
select count(*) as allnum from `oper_user` // as 取别名

select max(`id`) from `oper_user` // 查詢表中最大的id值
select min(`id`) from `oper_user` // 查詢表中最小的id值
select avg(`id`) from `oper_user` // 查詢表中id的平均值
select sum(`id`) from `oper_user` // 表中所有id的和           

增加:

insert into 表名 (字段1,字段2,字段3) values(字段1的值,字段2的值,字段3的值) //            

修改:

update 表名 set 字段名=字段值
update 表名 set 字段1=字段1的值,字段2=字段2的值 where 條件
update `oper_user` set `username`='admin',`password`='admin123' where `id`=2           

删除:

delete from 表名 where 條件
delete from `oper_user` where `id`=1