MySQL的基本命令
数据库的基本操作
1.【增】创建/删除数据库
sql
create database 数据库名称;
drop database db1;
【查】展示所有的数据库
sql
show databases;

使用某个数据库
sql
use test;
数据表的基本操作
1.增
sql
create table 表名(
字段1 字段类型,
字段2 字段类型,
...
字段n 字段类型
);
例如
create table student(
id int,
name varchar(20),
gender varchar(10),
birthday date
);
2.删
sql
drop table stu;
3.改字段alter
sql
alter table student rename to stu; //修改表名
alter table stu change name sname varchar(10); //修改字段名 change
alter table stu modify sname int; //修改字段类型 modify
alter table stu add address varchar(50); //添加字段 add
4.查
sql
show tables;
这个数据库里有哪些表
sql
desc student;
这个表有哪些字段
约束
表的约束实际上就是表中字段的限制条件。
- 主键约束【唯一且不空】
sql
字段名 数据类型 primary key;
- 非空约束
sql
字段名 数据类型 NOT NULL;
create table student02(
id int
name varchar(20) not null
);
- 默认值约束
sql
字段名 数据类型 DEFAULT 默认值;
create table student03(
id int,
name varchar(20),
gender varchar(10) default 'male'
);
- 唯一性约束
sql
字段名 数据类型 UNIQUE;
- 外键约束
建立外键就是想要保证 主表中的主键字段 与 从表中的外键字段 。这两个字段的统一,一个删除,对另一个有影响。具体是什么影响是需要diy的。
sql
ALTER TABLE 从表名 ADD CONSTRAINT 外键名 FOREIGN KEY (从表外键字段) REFERENCES 主表 (主键字段);
创建一个学生表 MySQL命令:
create table student05(
id int primary key,
name varchar(20)
);
创建一个班级表 MySQL命令:
create table class(
classid int primary key,
studentid int
);
alter table class add constraint fk_class_studentid foreign key(studentid) references student05(id);
数据表插入数据
这里有一张表
sql
create table student(
id int,
name varchar(30),
age int,
gender varchar(30)
);
插入
INSERT INTO 表名(字段名1,字段名2,...) VALUES (值 1,值 2,...);
insert into student (id,name,age,gender) values (1,'bob',16,'male');
更新
sql
UPDATE 表名 SET 字段名1=值1[,字段名2 =值2,...] [WHERE 条件表达式];
//将name为tom的记录的age设置为20并将其gender设置为female
update student set age=20,gender='female' where name='tom';
删除
sql
DELETE FROM 表名 [WHERE 条件表达式];
//删除age=14的
delete from student where age=14;
查询
sql
select * from student;
* 是所有的字段

sql
select sid,sname from student;
//查询指定字段(sid、sname)

条件查询where
sql
select * from student where age>=17;
