1.MySQL数据类型
数值类型:
日期和时间类型:
字符串类型:
2.MySQL相关语句
(1)创建数据库:create database 数据库名;
(2)删除数据库:drop database 数据库名;
(3)选择数据库:use 数据库名;
(4)创建数据库表:create table 表名(列名 类型);
(5)删除数据表:drop table 表名;
(6)插入数据:insert into 表名 (列名,列名...) values (value1,value2,...)
(7)查询数据表中数据:select * from 表名;
(8)查询数据表中部分数据:select 列名 from 表名;
3.Mysql where 语句
条件查询,可以在where语句中指定任何条件,可以使用and 或or指定一个或多个条件。
根据MySQL表中的字段值来获取指定数据。
例:查询性别是男的学生的id号和姓名:
select student_id,student_name from t_student where sex='男';
binary关键字
mysql的where子句的字符串比较是不区分大小写的,可以使用binary关键字来设定where自居的字符串比较是区分大小写的。
group by
对select查询出来的结果集按照某个字段或者表达式进行分组,获得一组集合。
having:
用于对where和group by 查询出来的分组进行过滤,查出满足条件的分组结果,与group by连用。
order by:
排序,asc:升序,desc:降序
如果字符集采用的是gbk(汉字编码字符集),直接在查询语句后边添加order by
如果字符集采用utf8(万国码),需要先对字段进行转码然后排序
4.Mysql update 语句
使用update语句更新数据表中的记录。
update 表名 set 属性名=value where。。。
可以同时更新一个或多个字段,可以通过where指定条件。
例:将lili的年龄修改为21岁
update t_student set age=21 where student_name='lili';
5.Mysql delete 语句
delete语句来删除mysql数据表中的数据
delete from 表名 where。。。
如果没有where子句,数据表中所有记录都会被删除。
delete和drop的区别
drop一般用于删除整体性数据,如表,模式,索引,视图,完整性限制等;drop是数据库定义语言(ddl)操作立即生效,不能回滚,操作不触发触发器。
delete用于删除局部性数据,如表中某一元组;delete语句是数据库操作语言(dml),在事务提交生效后,执行时触发相应的触发器。
6.Mysql like 语句
有时候我们需要获取字段中含有部分字符的所有记录,这时我们就可以在where中使用like语句。
like语句中使用%来表示任意字符。
例:获取表中学生姓名中含有AN字符的全部学生
select *from t_student where student_name like '%AN%';
like匹配/模糊匹配,会与%和_结合使用。
7.mysql union操作符
mysql union操作符用于连接两个以上的select语句结果组合到一个结果集合中。
语法格式:select 属性1,属性2,。。。
from 表名 where 。。。
union [all | distinct] distinct:删除结果集中重复的数据。
select 属性1,属性2,。。。
from 表名 where 。。。;
例:获取所有学生名字,去重
SELECT student_name FROM t_student
UNION distinct
SELECT student_name FROM t_course
ORDER BY student_name;
不去重:
SELECT student_name FROM t_student
UNION all
SELECT student_name FROM t_course
ORDER BY student_name;
带有where的union all:
SELECT student_name,student_id FROM t_student where student_name='wangyu'
UNION all
SELECT student_name,course_id FROM t_course where student_name='wangyu'
ORDER BY student_name;
8.mysql连接的使用
多表连接使用时用join连接。
inner join(内连接,或等值连接):获取两个表中字段匹配关系的记录。
left join(左连接):获取左表所有记录,即使右表没有对应匹配的记录。
right join(右连接):与left join相反,用于获取右表所有的记录
(1)inner join
例:select s.student_id,s.student_name,c.course_id from t_student s inner join t_course c on s.student_name=c.student_name;
等价于
select s.student_id,s.student_name,c.course_id from t_student s ,t_course c
where s.student_name=c.student_name;
(2) left join:
select s.student_id,s.student_name,c.course_id from t_student s left join t_course c on s.student_name=c.student_name;
(3)right join
select s.student_id,s.student_name,c.course_id from t_student s right join t_course c on s.student_name=c.student_name;
9.mysql null值处理
MySQL提供了三大运算符:
is null:当列的值是null,此运算符返回true。
is not null:当列的值不为null,运算符返回true。
<=>:比较操作符,当比较的两个值相等或者都为null时返回true。
10.mysql索引
MySQL索引的建立对于MySQL的高效运行是很重要的,索引可以大大提高MySQL的检索速度。
普通索引:
创建索引:create index 索引名 on 表名 (属性名);
修改表结构(添加索引):alter table 表名 add index 索引名(属性名);
唯一索引:
创建索引:create unique index 索引名 on 表名 (username(length));