基本sql语句

基本sql语句

1.数据库操作

1.1查看所有数据库
show databases;
1.2查看当前使用的数据库
select database();
1.3创建数据库
create databases 库名 charset=utf8;
1.4删除数据库
drop database 库名;
1.5使用数据库
use 库名;

2.数据表操作

2.1查看数据库中所有表

show tables;

2.2查看表结构

desc 表名;

2.3创建表

create table 表名(
	字段1 数据类型 可选约束条件;
	字段2 数据类型 可选约束条件;
	...
)

2.4删除表

drop table 表名;

2.5修改表结构 alter

# 添加新字段到数据表中。默认在最后加入新字段
alter table 表名 add 添加字段 数据类型;

# 添加新字段到数据表中,要求新字段在指定字段之后
alter table 表名 add 新字段 数据类型 after 指定字段;

# 删除指定字段
alter table 表名 drop 字段名;

# 修改指定字段
# modify 是修改字段对应数据类型
alter table 表名 modify 字段名 数据类型;

# change 修改字段名称和数据类型
alter table 表名 change 字段名 修改后字段名 数据类型;

3.表中数据操作

3.1添加数据

insert into 表(字段1,字段2) values(数据1,数据2);

3.2删除数据

# 不重置键操作
delete from 表名;
# 重置键操作
truncate 表名;

3.3修改数据

update 表名 set 字段1=数据1, 字段2=数据2;

3.4查询数据

select * from 表名

3.5排序 order by

# 根据指定字段排序  升序asc 降序 desc
select * from 表 order by 字段 asc/desc;

3.6条件限制where

update 表名 set 字段1=数据1, 字段2=数据2 where 限制条件;
delete * from 表 where 限制条件;
select * from 表 where 限制条件;

3.7=等值

select * from 表 where 字段=某值;

3.8 > < >= <= != <>关系运算符

select * from 表 where  字段>某值;

3.9逻辑判断(and, or, not)

# 查询表中字段不是某值的数据
select * from 表 where 字段 not 某值;

3.10 区间 between and

# 查询表中指定字段再范围区间值1-值2的数据
select *  from 表 where bettween 值1 and 值2;

3.11 is null is not null值判定

# 表中指定字段为空/不为空的数据
select * from 表 where 字段 is null;
select * from 表 where 字段 is not null;

3.12枚举查询 in

# 查询表中指定字段是枚举中具体值的数据
select * from 表 where 字段 in ( 值1,值2,值3);

3.13模糊查询 like

# _ 要求匹配一个字符
# % 不限制匹配字符数
# 要求以某字结尾,之前字符个数不限制
select * from 表 where 字段 like "%三";

3.14分组查询 group by

按照表中指定字段分组,查看每个组的人数
select 字段1,count(字段1)
from 表
group by 字段1;

3.15限定查询 limit

# 查询五条数据,从第一条开始
select * from 表
limit 0,5;
# 从开始查询十条数据
select *
from 表
limit 10;

4.子查询

将一条查询语句的查询结果作为另一条查询语句的一部分进行查询

select fieldName
from tbName
where (子查询结果);

5.多表查询

select 字段名称
from 表1,表2
where 限制条件

5.1内连接查询inner join on

select 字段名
from 表1
inner join 表2 on 表1.字段 = 表2.字段

5.2左外连接left join on

# 左侧为主表 完整展示 若右表中没有对应数据 显示null
select 字段名
from 表1
left outer join 表2 on 表1.字段 = 表2.字段

5.3右外连接 right join on

# 右侧为主表 完整展示 若左表中没有对应数据 显示null
select 字段名
from 表1
right outer join 表2 on 表1.字段 = 表2.字段
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值