mysql语法
字段类型
- 数字:int,decimal
- 字符串:char,varchar,text
- 日期:datetime,timestamp
- 布尔值:bit
数据库操作
- 创建数据库
create database 数据库名 charset=utf8;
- 删除数据库
drop database 数据库名;
- 切换数据库
use 数据库名;
- 查看当前选择的数据库
select database();
表操作
- 查询
select * from 表名
- 增加
全列插入:insert into 表名 values(...) 缺省插入:insert into 表名(列1,...) values(值1,...) 同时插入多条数据:insert into 表名 values(...),(...)...; 或insert into 表名(列1,...) values(值1,...),(值1,...)...;
- 主键列是自动增长,但是在全列插入时需要占位,通常使用0,插入成功后以实际数据为准
- 修改
update 表名 set 列1=值1,... where 条件
- 删除
delete from 表名 where 条件
- 逻辑删除,本质就是修改操作update
alter table students add isdelete bit default 0; 如果需要删除则 update students isdelete=1 where ...;
数据查询
条件
- 使用where子句对表中的数据筛选,结果为true的行会出现在结果集中
select * from 表名 where 条件;
- 比较运算符
- 等于=
- 大于>
- 大于等于>=
- 小于<
- 小于等于<=
- 不等于!=或<>
查询编号大于3的学生
select * from students where id>3;
- 逻辑运算符
- and
- or
- not
//查询编号大于3的女同学
select * from students where id>3 and gender=0;
//查询编号小于4或没被删除的学生
select * from students where id
- 模糊查询
- like
- %表示任意多个任意字符
- _表示一个任意字符
查询姓黄的学生
select * from students where sname like ‘黄%‘;
查询姓黄并且名字是一个字的学生
select * from students where sname like ‘黄_‘;
查询姓黄或叫靖的学生
select * from students where sname like ‘黄%‘ or sname like ‘%靖%‘;
- 范围查询
- in表示在一个非连续的范围内
- between ... and ...表示在一个连续的范围内
查询编号是1或3或8的学生
select * from students where id in(1,3,8);
查询学生是3至8的学生
select * from students where id between 3 and 8;
查询学生是3至8的男生
select * from students where id between 3 and 8 and gender=1;
- 空判断
注意:null与‘‘是不同的
判空is null
查询没有填写地址的学生
select * from students where hometown is null;
判非空is not null
查询填写了地址的学生
select * from students where hometown is not null;
查询填写了地址的女生
select * from students where hometown is not null and gender=0;
聚合
- count(*)表示计算总行数,括号中写星与列名,结果是相同的
查询学生总数
select count(*) from students;
- max(列)表示求此列的最大值
查询女生的编号最大值
select max(id) from students where gender=0;
- min(列)表示求此列的最小值
查询未删除的学生最小编号
select min(id) from students where isdelete=0;
- sum(列)表示求此列的和
查询男生的编号之后
select sum(id) from students where gender=1;
- avg(列)表示求此列的平均值
查询未删除女生的编号平均值
select avg(id) from students where isdelete=0 and gender=0;
分组
按照字段分组,表示此字段相同的数据会被放到一个组中; 分组后,只能查询出相同的数据列,对于有差异的数据列无法出现在结果集中 ;可以对分组后的数据进行统计,做聚合运算
语法
select 列1,列2,聚合... from 表名 group by 列1,列2,列3...
查询男女生总数
select gender as 性别,count(*) from students group by gender;
查询各城市人数
select hometown as 家乡,count(*) from students group by hometown;
- 分组后的数据筛选
语法
select 列1,列2,聚合... from 表名 group by 列1,列2,列3... having 列1,...聚合...
//having后面的条件运算符与where的相同
//查询男生总人数
方案一 select count(*) from students where gender=1;
-----------------------------------
方案二: select gender as 性别,count(*) from students group by gender having gender=1;
- 对比where与having
- where是对from后面指定的表进行数据筛选,属于对原始数据的筛选
- having是对group by的结果进行筛选
排序
语法
select * from 表名 order by 列1 asc|desc,列2 asc|desc,...
- 将行数据按照列1进行排序,如果某些行列1的值相同时,则按照列2排序,以此类推
- 默认按照列值从小到大排列
- asc从小到大排列,即升序
- desc从大到小排序,即降序
查询未删除男生学生信息,按学号降序
select * from students where gender=1 and isdelete=0 order by id desc;
查询未删除科目信息,按名称升序
select * from subject where isdelete=0 order by stitle;
- 获取部分行
语法
select * from 表名 limit start,count
从start开始,获取count条数据;start索引从0开始
外键
为stuid添加外键约束
alter table scores add constraint stu_sco foreign key(stuid) references students(id);
create table scores(
id int primary key auto_increment,
stuid int, subid int, score decimal(5,2),
foreign key(stuid) references students(id),
foreign key(subid) references subjects(id) );
- 外键的级联操作
语法
alter table scores add constraint stu_sco foreign key(stuid) references students(id) on delete cascade;
- 级联操作的类型包括:
- restrict(限制):默认值,抛异常
- cascade(级联):如果主表的记录删掉,则从表中相关联的记录都将被删除
- set null:将外键设置为空
- no action:什么都不做
连接查询
- 连接查询分类如下:
- 表A inner join 表B:表A与表B匹配的行会出现在结果中
- 表A left join 表B:表A与表B匹配的行会出现在结果中,外加表A中独有的数据,未对应的数据使用null填充
- 表A right join 表B:表A与表B匹配的行会出现在结果中,外加表B中独有的数据,未对应的数据使用null填充
//查询学生的姓名、平均分
select students.sname,avg(scores.score) from scores inner join
students on scores.stuid=students.id group by students.sname;
//查询男生的姓名、总分
select students.sname,avg(scores.score) from scores inner join
students on scores.stuid=students.id where students.gender=1 group by students.sname;
//查询科目的名称、平均分
select subjects.stitle,avg(scores.score) from scores inner join
subjects on scores.subid=subjects.id group by subjects.stitle;
//查询未删除科目的名称、最高分、平均分
select subjects.stitle,avg(scores.score),max(scores.score) from scores
inner join subjects on scores.subid=subjects.id where subjects.isdelete=0
group by subjects.stitle;
字符串函数
- 查看字符的ascii码值ascii(str),str是空串时返回0
select ascii(‘a‘);
- 查看ascii码值对应的字符char(数字)
select char(97);
- 拼接字符串concat(str1,str2...)
select concat(12,34,‘ab‘);
- 包含字符个数length(str)
select length(‘abc‘);
- 截取字符串
- left(str,len)返回字符串str的左端len个字符
- right(str,len)返回字符串str的右端len个字符
- substring(str,pos,len)返回字符串str的位置pos起len个字符
select substring(‘abc123‘,2,3);
- 去除空格
- ltrim(str)返回删除了左空格的字符串str
- rtrim(str)返回删除了右空格的字符串str
- trim([方向 remstr from str)返回从某侧删除remstr后的字符串str,方向词包括both、leading、trailing,表示两侧、左、右
select trim(‘ bar ‘); select trim(leading ‘x‘ FROM ‘xxxbarxxx‘); select trim(both ‘x‘ FROM ‘xxxbarxxx‘); select trim(trailing ‘x‘ FROM ‘xxxbarxxx‘);
- 返回由n个空格字符组成的一个字符串space(n)
select space(10);
- 替换字符串replace(str,from_str,to_str)
select replace(‘abc123‘,‘123‘,‘def‘);
- 大小写转换,函数如下
- lower(str)
- upper(str)
数学函数
- 求绝对值abs(n)
select abs(-32);
- 求m除以n的余数mod(m,n),同运算符%
select mod(10,3); select 10%3;
- 地板floor(n),表示不大于n的最大整数
select floor(2.3);
- 天花板ceiling(n),表示不小于n的最大整数
select ceiling(2.3);
- 求四舍五入值round(n,d),n表示原数,d表示小数位置,默认为0
select round(1.6);
- 求x的y次幂pow(x,y)
select pow(2,3);
- 获取圆周率PI()
select PI();
- 随机数rand(),值为0-1.0的浮点数
select rand();
- 日期计算,使用+-运算符,数字后面的关键字为year、month、day、hour、minute、second
select ‘2016-12-21‘+interval 1 day;
- 当前日期current_date()
select current_date();
- 当前时间current_time()
select current_time();
视图
视图本质就是对查询的一个封装
create view stuscore as select students.*,scores.score from scores inner join students on scores.stuid=students.id;
conn=connect(参数列表)
- 参数host:连接的mysql主机,如果本机是‘localhost‘
- 参数port:连接的mysql主机的端口,默认是3306
- 参数db:数据库的名称
- 参数user:连接的用户名
- 参数password:连接的密码
- 参数charset:通信采用的编码方式,默认是‘gb2312‘,要求与数据库创建时指定的编码一致,否则中文会乱码
Cursor对象
对象的方法
- close()关闭
- execute(operation [, parameters ])执行语句,返回受影响的行数
- fetchone()执行查询语句时,获取查询结果集的第一个行数据,返回一个元组
- next()执行查询语句时,获取当前行的下一行
- fetchall()执行查询时,获取结果集的所有行,一行构成一个元组,再将这些元组装入一个元组返回
- scroll(value[,mode])将行指针移动到某个位置
- mode表示移动的方式
- mode的默认值为relative,表示基于当前行移动到value,value为正则向下移动,value为负则向上移动
- mode的值为absolute,表示基于第一条数据的位置,第一条数据的位置为0
python操作mysql
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
# 创建连接
conn = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘123‘, db=‘t1‘)
# 创建游标
cursor = conn.cursor()
# 执行SQL,并返回收影响行数
effect_row = cursor.execute("update hosts set host = ‘1.1.1.2‘")
# 执行SQL,并返回受影响行数
#effect_row = cursor.execute("update hosts set host = ‘1.1.1.2‘ where nid > %s", (1,))
# 执行SQL,并返回受影响行数
#effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])
# 提交,不然无法保存新建或者修改的数据
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()