mysql之数据类型

 所谓建表,就是声明列的过程:

  数据是以文件的形式放在硬盘中(也有放在内存里的)

 列:不同的列类型占的空间不一样

  选列的原则:够用又不浪费;

     mysql的数据类型:

  整形:Tinyint(1字节)  Smallint(2个字节)  Mediumint(3个字节)  int(4个字节)  bigint(8个字节);

  Tinyint在mysql默认是有符号的(-128----127);

Tinyint(M) unsigned zerofill
unsigned : 是无符号,影响存储范围;
M代表宽度,(必须配合zerofill时才有意义)
Zerofill 零填充,如果某列是zerofill,默认是unsigned(类似00005);

insert into classs (name, age4)values (‘zhaoliu‘, 9);
列可以声明默认值,而且推荐声明默认值
Not NULL default 0

alter table class add age5 tinyint not null default 0;

小数型/浮点型定点型:
  Float(M, D)
  decimal(M, D)
  //M:精度(总位数,不包含点) D:标度(小数位)

create table goods(
name varchar(10) not null default ‘‘,
price float(6, 2) not null default 0.00) //9999.99, -9999.99
//price float(6, 2) unsigned not null default 0.00) //0-9999.99,
charset utf8;

inert into goods
(name, price)
values
(‘跑步机‘, ‘688,896’)
//记录在表中price的值为688.90

alter table goods add bigprice float(9.2) not null default 0.0;

alter table goods add deciprice decimal(9.2) not null default 0.0;

alter table goods (name, bigprice, deciprice)
values
(‘自行车‘, 1234567.23, 1234567.23);

 

字符型
char 定长字符串 char(M),M代表宽度,即可容纳的字符数;
Varchar 变长字符串 Varchar(M),M代表宽度,即可容纳的字符数;

区别:
char定长: M个字符如果存的小于M个字符,实占M个字符;利用率是100%
varchar变长: M个字符如果存的小于M个字符,假设为N,实占N个字符;
实占的字符需要记录消耗1--2个字符;实际占有(N+1~2)个字符;

char 与varchar选择原则:
1、空间利用效率;
2、速度;
四字成语表,char(4);
个人微博, varchar(140);

用户名:char,牺牲空间,提供速度;
text 文本串,比较大段文本,速度稍慢;
注意:text不要加默认值,加了也不生效;


create table stu(
name char(8) not null default ‘‘,
waihao varchar(16) not null default ‘‘
)charset utf8; //name最多容纳8个utf8字符;

insert into stu(name, waihao)
values
(‘zhangxiaosan‘, ‘saner‘); //拆入不进去,zhangxiaosan太长了;

insert into stu(name, waihao)
values
(‘zhangsan‘, ‘saner‘);

insert into stu(name, waihao)
values
(‘默罕默德买买提‘,‘异步拉欣’);

select concat (name, ‘!‘), concat(waihao, ‘!‘) from stu;

alter table std add info text not null default ‘‘;
//执行错误;不能默认值;

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。