Level 1: Create a database
Connect to MySQL on the right command line and create a database named MyDb .
The user name to connect to the database is: root , and the password is: 123123 .
mysql -uroot -p123123 -h127.0.0.1
create database MyDb
Level 2: Creating Tables
Operate in the command line on the right, create the database TestDb , and create the table t_emp under TestDb . The table structure is as follows:
Field Name |
type of data |
Remark |
id |
INT |
employee ID |
name |
VARCHAR(32) |
employee name |
deptId |
INT |
Department number |
salary |
FLOAT |
salary |
mysql -uroot -p123123 -h127.0.0.1
use TestDb
create table t_emp(
id int,
name varchar(32),
deptId int,
salary float
);
Level 3: Using primary key constraints
In the database MyDb , create two tables t_user1 and t_user2 . The table structure is as follows. Please create primary key constraints for the two tables respectively. The primary key of t_user1 is userId , the primary key of t_user2 is the joint primary key, and the fields name and phone are used as the joint primary key of t_user2 .
Table t_user1
field name |
type of data |
Remark |
userId |
INT |
User ID |
name |
VARCHAR(32) |
username |
password |
VARCHAR(11) |
password |
phone |
VARCHAR(11) |
telephone number |
VARCHAR(32) |
table t_user2
field name |
type of data |
Remark |
name |
VARCHAR(32) |
username |
phone |
VARCHAR(11) |
telephone number |
VARCHAR(32) |
create database MyDb
use MyDb
create table t_user1(
userId int primary key,
name varchar(32),
password varchar(11),
phone varchar(11),
email varchar(32)
);
create table t_user2(
name varchar(32),
phone varchar(11),
email varchar(32),
primary key(name,phone)
);
Level 4: Foreign key constraints
创建两张表如下,给t_student表添加外键约束,外键为classId,外键名称为fk_stu_class1。
表t_class
字段名称 |
数据类型 |
备注 |
id |
INT |
班级Id,主键 |
name |
VARCHAR(22) |
班级名称 |
表t_student
字段名称 |
数据类型 |
备注 |
id |
INT |
学号,主键 |
name |
VARCHAR(22) |
学生姓名 |
classId |
INT |
班级ID,外键 |
在创建表之前你需要先创建数据库:MyDb,并且将两张表创建在MyDb数据库中。
mysql -uroot -p123123 -h127.0.0.1
create database MyDb;//已经创建了的就无需再创建了
use MyDb
create table t_class(
id int primary key,
name varchar(22)
);
create table t_student(
id int primary key,
name varchar(22),
classId int,
constraint fk_stu_class1 foregin key(classId) references t_class(id)
);
第5关:添加常用约束
在数据库MyDb中创建表t_user,表结构如下:
字段名称 |
数据类型 |
备注 |
id |
INT |
用户ID,主键,自动增长 |
username |
varchar(32) |
用户名,非空,唯一 |
sex |
varchar(4) |
性别,默认“男” |
提示:若要给字段添加两个或者两个以上的约束,约束之间以空格隔开即可。
mysql -uroot -p123123 -h127.0.0.1
create database MyDb;
use MyDb
create table t_user(
id int primary key auto_increment,
username varchar(32) not null unique,
sex varchar(4) default '男'
)default charset = utf8;