整数int
小整数tinyint
小数decimal
字符串varchar
日期时间datetime
database数据库table表field列,字段
record记录,行
- create table 创建表
create table表名(字段名 数据类型(字符长度),字段名 数据类型());
- insert增
insert into X values(…,…);
在表X中插入此数据。
insert into X (ID,name) values (3,'曹操');只添加ID和name
在表X中插入3和曹操
insert into X values(5,'犹豫',90);
insert into X(ID,name) values (6,'鲁肃');
insert into X (name) values ('纣王');
多条insert语句用;分开。
insert into X values(……),(……);
一条insert语句添加多条。
- update改
语法update 表名 set 字段=值,字段=值where 条件;
update X set age=50;把表X中所有的age改为50
update X set age=50,name='狗蛋' where ID=2;把ID为2的age改为50name改为狗蛋。
4、select查询
语法:select* from 表名
select* from X;查询表X所有数据
select ID from X;查询表X中的ID字段
select now();
5、delete删除数据
语法:delete from 表名 where 条件;
delete from X where ID=6;
删除表中ID为6的记录
delete from X;
删除表X的所有记录。
truncate table 表名;没有条件
删除表中所有数据。
速度上truncate>delete
如果想删除部分数据用delete,注意加上where子语句
如果想保留表而将所有数据删除,自增长字段恢复从1开始,用truncate,
6、drop table删除表
语法:drop table 表名;
drop table X;删除表X。
drop table if exists B;删除表B,如果B不存在什么都不做。
约束
主键(primary key)值不能重复
auto_increment代表值自动增长
非空(not null)此字段不允许填写空值
唯一(unique)此字段的值不允许重复
默认值(default)当不填写此值时会使用默认值,如果填写以填写为准
总结:创建表create table
删除表drop table 表/drop table if exists 表名
插入记录insert into
查询表select * from 表名
修改记录 update 表名 set 字段=值 where 条件
删除记录delete from 表名 where条件
truncate table 表名
第二部分
1、查询所有字段
select * from X 查询X表中的所有字段
select name,sex from X查询X表name和sex字段
2、通过as给字段起一个别名
select card as 身份证,name as 姓名,sex as 性别 from X
别名的as可以省略
select card 身份证,name 姓名,sex 性别from X;
字段名as 别名和字段名 别名的结果是一样的
- 通过as给表X起一个别名
select * from X as putong;
可以省略as
select * from X putong;
- 消除重复记录distinct.
select distinct * from X;
5、where子语句
查询X表中学生ID等于'222'的记录
select * from X where ID='222';
- 查询X表中年龄age等于30的姓名name,班级class
select name,class from X where age=30;
- select后面的*或字段名,决定了返回什么样的字段(列)
select中的where子句,决定了返回什么样的记录(行)
8、where后面支持多种运算符,进行条件的处理
比较运算、逻辑运算、模糊查询、范围查询、空判断
逻辑运算and、or、not
模糊查询
select * from X where name like '孙%';查询X表中姓孙的人员
select * from X where name like '孙_';
查询X表中姓孙并且两个字的人员
select * from X where name like '%阿%'
查询姓名中带有阿的同学
范围查询
查询家乡在北上广的学生记录
select * from X where hometown='北京'or hometown='上海'or hometown='深圳';
select * from X where hometown in ('北京','上海','深圳');
查找age年龄在25至30的学生的记录
select * from X where age>=25 and age<=30;
select * from X where age between 25 and 30;
空判断
null不是0也不是空
null不能用比较运算符判断
查询card身份证为null的学生的记录
select * from X where card is null;
查询card身份证不为空的学生的记录
select * from X where card not is null;
修改age年龄为25且name为'孙俪'的学生class为'2班'
update X set class ='2班' where age=25 and name='孙俪';
删除class为'1班',并且age大于3