表操作
创建:
CREATE TABLE 表名 (
属性名 数据类型 [完整约束条件],
属性名 数据类型 [完整约束条件],
...
...
属性名 数据类型 [完整约束条件]
);
#create table student (id int not null,name varchar(20) not null,sex varchar(20) default 'male',primary key (id));
其中,完整性约束:
PRIMARY KEY (PK) 标识该字段为该表的主键,可以唯一的标识记录
FOREIGN KEY (FK) 标识该字段为该表的外键
NOT NULL 标识该字段不能为空
UNIQUE KEY (UK) 标识该字段的值是唯一的
AUTO_INCREMENT 标识该字段的值自动增长(整数类型,而且为主键)
DEFAULT 为该字段设置默认值
-- 删除主键约束
alter table temp drop primary key;
-- 添加主键约束
alter table temp add primary key(id);
-- 修改主键约束
alter table temp modify id int primary key;
-- 删除外键约束
alter table student drop foreign key student_id;
-- 增加外键约束
alter table student add foreign key(classes_name, classes_number) references classes(name, number);
-- 添加唯一约束
alter table temp add unique (name, password);
-- 修改唯一约束
alter table temp modify name varchar(25) unique;
-- 删除约束
alter table temp drop index name;
-- 增加非空约束
alter table temp
modify sex varchar(2) not null;
-- 取消非空约束
alter table temp modify sex varchar(2) null;
-- 取消非空约束,增加默认值
alter table temp modify sex varchar(2) default 'abc' null;
删除
#drop table student;
修改表名 :ALTER TABLE 旧表名 RENAME 新表名;
#alter table student rename student1;
修改字段类型:ALTER TABLE 表名 MODIFY 属性名 数据类型;
#alter table student1 modify name varchar(25);
修改字段名:ALTER TABLE 表名 CHANGE 旧属性名 新属性名 新数据类型;
#alter table student1 change name stu_name varchar(20);
增加字段:ALTER TABLE 表名 ADD 属性名 数据类型;
#alter table student1 add teacher_name varchar(20) not null;
删除字段:ALTER TABLE 表名 DROP 属性名;
#alter table student1 drop teacher_name;
数据操作
增加一条数据:INSERT INTO 表名 VALUES(值11,值2,…);
#insert into student1 values (1,'xiaoming','male');
删除一条数据:DELETE FROM 表名 [WHERE 条件表达式;
#delete from student1 where stu_name='xiaoming';
若 DELETE 语句中没有使用WHERE语句,则会将表中所有记录都删除
更新一条数据:
UPDATE 表名 SET 字段名1=值1,[ ,字段名2=值2,…] [ WHERE 条件表达式 ]
#update student1 set sex='female' where id=1;
在UPDATE 语句中若不使用WHERE 子句,则会将表中所有记录的指定字段都进行更新。
查询:
空值查询:select * from student2 where gender is null;
通配符%查询:%匹配任意长度的字符串,包括空字符串
#SELECT id,name FROM student2 WHERE name LIKE "S%";
通配符_查询:下划线通配符只匹配单个字符,若要匹配多个字符,需要使用多个下划线通配符
SELECT * FROM student2 WHERE name LIKE 'wu_ong';
其他:
on update cascade 和on delete cascade 的区别:https://blog.youkuaiyun.com/ufan94/article/details/84138278