创建 create table
删除 drop table
查看表结构 desc 表/show create table 表
修改
alter table 表名 rename 新表名
alter table 表名 add 新字段 类型(宽度) 约束 first、after 已有字段(位置)
alter table 表名 change 旧字段 新字段 类型(宽度) 约束 first、after 已有字段;
#旧字段 旧字段 类型(宽度) 约束 first、after 已有字段;
alter table 表名 modify 已有字段 类型(宽度) 约束 first、after 已有字段;
alter table 表名 drop 字段名;
增
insert into 表名 value 单条数据;
insert into 表名 values 单/多条数据;
insert into 表名(字段1,字段2) values 数据; *****
insert into 表名(字段1,字段2) select (字段3,字段4) from 库.表名;
删 delete from 表名 where 条件
改
update 表名 set 字段=值 where 条件;
update 表名 set 字段1=值1,字段2=值2 where 条件;
查 单/多表查询
select 想要的列 from 表
where 先从这张表中查询的行
group by 分组
having 对组过滤
order by 排序
limit 取一个区间
select user(); 查询当前账户
select database(); 查看当前库
select now(); 查看当前时间
1.简单查询
select * from 表名;
select 字段名 from 表名;
select 字段名,字段名,字段名 from 表名;
2.distinct 去重
select distinct 字段 from 表名;
3.四则运算
select 字段*12 from 表名
4.concat
select concat(字段,'字符串',字段)as(可以不写) 该组合字段的名称 from 表名;
select concat_ws('分隔符','字符串',字段,字段)as 该组合字段的名称 from 表名;
# 分隔符会出现在每个字符串和字段的中间,类似join
5.case 语句
select(
case
when 条件1 then
结果1
when 条件2 then
结果2
else
结果3
end
) as 该新生字段名称
from 表名;
select * from 表 where 条件
1.范围查询
> < >= <= = !=或<>
between a and b
in(a,b,c,d)
2.模糊查询
like:
% 代表任意长度的任意字符
'a%' 以a开头
'%a' 以a结尾
'%a%' 包含a
_ 代表一个任意字符
'蔡__' 蔡XX
regexp:正则大多数方法可运用于mysql
3.is,is not
is null
is not null
4.逻辑运算:and,or,not
根据某个重复率比较高的字段进行,该字段有多少种可能就分成多少组
分组后不能对具体对某一条数据进行操作,而是对该若干组进行操作
# 可去重
# group_concat:只用来做最终结果的显示,不能作为中间结果操作其他数据
基本上都是和分组一起使用,如果没有和分组一起用,默认一整张表为一组
count 计数 count(id)/count(*) 每组对应的数据数
max 最大值:这个组中某字段的最大值
min 最小值:这个组中某字段的最小值
avg 平均值
sum 求和
select min(hire_date) from employee group by post; #求每个部门入职最早的时间
就是对组进行筛选的条件
select post from employee group by post having count(id)>3; # 人数大于3的部门
having的问题:select或group by的字段里必须包含having条件中的字段,所以不推荐使用
order by 字段 默认升序
order by 字段 asc 升序
order by 字段 desc 降序
order by 字段1,字段2
order by 字段1 asc,字段2 desc
order by 字段1 desc,字段2 asc
order by 字段1 desc,字段2 desc
1.显示分页
limit m,n 或 limit n offset m # 表示从m+1开始,取n条
2.取前n名
limit n # m默认为0,通常与order by 一起用
import pymysql
conn = pymysql.Connection(host='127.0.0.1', user='root', password="123",database='day40')
cur = conn.cursor() # 游标 数据库操作符
cur.excute(sql,(值1,值2,值3,))
# 查询
sql = 'select 字段1,字段2 from 表 where 字段 = %s'
# 条件里字段的值可以为%s,在cur.excute中以元组形式填值
cur.excute(sql,(值,))
cur.fetchone()/cur.fethmany(3)/cur.fetchall() #获取结果
# 插入/更新/删除
sql = 'insert into 表(字段1,字段2,字段3) values(%s,%s,值)
# 数据中的值可以为%s,在cur.excute中以元组形式填值
cur.excute(sql,(值1,值2))
conn.commit()
cur.close()
conn.close()
原文:https://www.cnblogs.com/wxl1025/p/11283737.html