Mysql问题汇总&学习记录2:Mysql日期类型、字符类型以及各表之间的连接关系

MySQL学习记录2

日期类型

create table student(
    id int,
    name char(6),
    born_year year,
    birth_date date,
    class_time time,
    reg_time datetime
);
insert into student values
(1,'egon',now(),now(),now(),now());

*如果有前文打错的代码且无法删除,可用/c结束当前语句。(终止运行)

datatime与timestamp区别
在这里插入图片描述

字符类型

char与varchar用法与区别

一个变长,一个定长。

char简单粗暴存取速度快,但浪费空间;varchar,更加节省空间,存取精准,存取的时候速度慢。现在大部分用char类型。最好不要混着用。
在这里插入图片描述

查询:select xxx from xxx where xxx = ‘x’;#使用时可以自动忽略数据后面的空格

​ select xxx from xxx where xxx like = ‘x’;#使用时空格数量等必须相同

枚举类型和集合类型

需要注意的是如果insert中选择了列表类型中没有的选项,则表格中不会显示。

约束条件

在这里插入图片描述
null/key/default/extra即为约束条件。

null:是否允许传空值。

default:出现错误时报告的值(可设置默认值)

扫描二维码关注公众号,回复: 16565186 查看本文章

**unique key:**可设置某数据不能重复:

单列唯一:

方式1:直接在字段后面加unique

create table department(
	id int,
	name char(10) unique
);

方法2:在末尾加unique(名字),

联合唯一(MUL):unique(名字,名字),

primary key:不为空且唯一 not null unique

存储引擎(inodb(默认)):对于innodb存储引擎来说,一张表内必须有一个主键。

建立主键:

#单列主键

create table t1(
	id int primary key,
	name char(16),
);

#复合主键

primary(名字,名字),

auto_increment:自增长

create table t20(
	id int primary auto_increment,#表明id可以自己从1往上增加。
	name char(16)
);

#如果insert的地方设置了一个其他id,则下一条无设置的id从该条开始自加。

#了解

	show variables like ’auto_inc%‘;
	#auto_increment_increment步长:默认为1
	auto_increment_offset起始偏移量:默认为1`

#设置步长(起始偏移量同理):

	set session auto_increment_increment=5;#局部
	set global auto_increment_increment=5;#全局,得退出重进

强调:起始偏移量≤步长。

foreign key:建立表之间的关系

1、建立表关系:

eg.#先建被关联的表,并且保证被关联的字段唯一。

create table dep(
	id int primary key,
	name char(16),
	comment char(50)
);

#再建关联的表

create table emp(
	id int primary key,
	name char(10),
	sex enum('male','female'),
	dep_id int,
	foreign key (dep_id)references dep(id)
    on delete cascade on update cascade #这里可实现自动更新自动删除
); 

查看表结构:desc dep;(复习一下)

2、插入数据:

#先往被关联表插入记录

insert into dep values
(1,"IT","123"),
(2,"销售","456"),
(3,"财务","789");

#再往关联表插入记录

insert into emp values
(1,'dumpling','male',1);

#删除不要的信息:

1、先删关联表,再删被关联表。

delete from emp where dep_id=1;
delete from dep where id = 1;

2、建立关联表时加入:on delete cascade on update cascade

可直接删除被关联表中内容:

delete from dep where id = 1;
update dep set id = 202 where id = 2;

dep where id = 1;


2、建立关联表时加入:on delete cascade on update cascade

可直接删除被关联表中内容:

```mysql
delete from dep where id = 1;
update dep set id = 202 where id = 2;

尽量不要这样使用,拓展的时候可能会出问题。

猜你喜欢

转载自blog.csdn.net/weixin_47723114/article/details/131791327