mysql最基本使用命令(外键,联合查询,事件)

Circle / 2025-01-25 / 原文

1. 创建一个表

create table class(id int not null primary key, name char(16));

# 插入数据

insert into class(id,name) values(1,"张三");

insert into class(id,name) values(2,"lisi");

2.创建一个表,带外键

create table student(id int(11) not null, name char(16) not null, class_id int(11) not null, primary key(id), key fk_class_key(class_id),  constraint fk_class_key foreign key (class_id) references class (id));

解析:

KEY fk_class_key (class_id):为 class_id 字段创建了一个索引,命名为 fk_class_key。这有助于提高基于 class_id 的查询性能。

CONSTRAINT fk_class_key FOREIGN KEY (class_id) REFERENCES class (id):定义了一个名为 fk_class_key 的外键约束,指定 student 表的 class_id 字段引用 class 表的 id 字段。这意味着 class_id 字段的值必须是 class 表中已存在的 id 字段的值。

 

# 插入数据

insert into student(id,name,class_id) values(202401,"zhangsan",1);

insert into student(id,name,class_id) values(202402,"lisi",2);

 

3.是否为空的判断

is null

is not null

 

 

4.联合查询

① inner join 内连接 (求两个表相同的部分,并集)

select * from A inner join B on A.a = B.b;

select A.*,B.* from A,B where A.a = B.b;

② left join 左连接(差集,以做为主)

select * from A left join B on A.a = B.b;

③ right join 右连接

select * from A right join B on A.a = B.b;

 

 

5.事件

begin; 命令 ; rollback;  回滚,不执行操作

begin; 命令 ; commit;  执行操作