MySQL基本语句
- 启动数据库
net start mysql
- 登陆
mysql -uroot -p
- 无密码登陆
mysql -uroot
- 查询本地数据库
show databases
- 建立数据库
create database *****;
当名字为保留字是要用英语的反引号括起来`` - 如何操作单个数据库
use ****
- 显示数据库中的表
show tables;
- 创建表
CREATE TABLE ****(
name VARCHAR(20),
owner VARCHAR(20),
species VARCHAR(20),
sex CHAR(1),
birth DATE,
death DATE);
- 查看所创建数据表的结构
describe ***;
- 查看表中的记录
select * from ***;
- 在表中加东西
INSERT INTO ***VALUES (' ', ' ', ' ' ,' ',NULL);
- 查询
select * from 表名
此处*表示查找全部 - 删除数据
delete from 表名 where *** ='***'
- 修改数据 `update 表名 set name =‘旺旺‘ where ****=’**’``
- 增加
INSERT
- 删除
DELETE
- 修改
UPDATE
- 查询
SELECT
MySQL建表约束
1. 主键约束
* 它能够唯一确定一张表中的一条记录,通过给某个字段添加约束,就可以使得该字段**不重复且不为空**。
create table 表名(
id int primary key,
name varchar(20)
);
insert into 表名 values(1,‘张三’); insert into 表名 values(1,‘张三’); 第二次添加报错,主键不可添加重复 insert into 表名 values(1,‘张三’);不可为空也会报错
联合主键只要组合加起来不一样即可,但都不可以为空
create table 表名(
id int,
name varchar(20)
primary key(id,name)
);
insert into 表名 values(1,‘张三’); insert into 表名 values(2,‘张三’);
此种情况 联合主键不会报错
2. 自增约束
create table ****(
id int primary key auto_increment,
name varchar(20)
);
insert into 表名 (name) values(‘张三’); insert into 表名 (name) values(‘张三’);
此时虽然没有添加ID,但是自增约束与主键约束结合,自动生成ID
如果事前没有加主键约束的办法
create table 表名(
id int,
name varchar(20)
);
alter table 表名 add primary key(id);
删除主键方法
create table 表名(
id int primary key,
name varchar(20)
);
alter table 表名 drop primary key(id);
使用 modify 修改字段,添加约束
create table 表名(
id int,
name varchar(20)
);
alter table 表名 modify id int primary key;
3. 唯一约束
约束修饰的字段的值不可以重复,重复就报错
create table 表名(
id int,
name varchar(20)
);
alter table 表名 add unique(name);
两个键组合不重复就可以
create table 表名(
id int,
name varchar(20)
unique(name,id)
);
create table 表名(
id int,
name varchar(20) unique
);
删除唯一约束方法
create table 表名(
id int,
name varchar(20)
unique(name)
);
alter table 表名 drop index name;
4. 非空约束
create table 表名(
id int not NULL,
name varchar(20)
);
alter table 表名 add unique(name);
5. 默认约束
当我们插入字段值的时候,如果没有传值,就会使用默认值
增加与删除与前几个一样
create table 表名(
id int ,
name varchar(20)
age int default 10
);
6.外键约束
涉及到:父表,子表
主表,副表
–班级
create table classes(
id int primary key,
name varchar(20)
);
–学生表
create table students(
id int primary key,
name varchar(20),
class_id int,
foreign key (class_id) references classes(id)
);
```
```sql
insert into classes values(1,'一班');
insert into classes values(2,'二班');
insert into classes values(3,'三班');
insert into classes values(4,'四班');
insert into students values(1001,'张三',1);
insert into students values(1002,'张三',2);
insert into students values(1003,'张三',3);
insert into students values(1004,'张三',4);
insert into students values(1005,'lisi',5);X
主表中不存在 副表会报错
主表中的记录被副表引用,是不可以被删除的
Xdelete from classes where id = 4;