当前位置:网站首页>Basic data types of MySQL
Basic data types of MySQL
2022-07-04 10:22:00 【Java full stack preacher】
What is the data type ? To put it bluntly, it is the storage format of data 、 Constraints and effective range .
Selection of data type , That is to specify the underlying data storage structure of different data , Directly affect the performance of the database .

The selection of data type is also an important point of database performance tuning , Learning data types carefully is also a preparation for learning database tuning in the future .
Start learning how to fish ……
How do I know which data types there are in the database ?
I talked about how to check it quickly in this article MySQL help : When I forget SQL How to write , I ……
Check the data types

Specific syntax and instructions for each data type

You can see the data type :int Specific syntax and instructions ( Mainly the effective range )
All the data types listed here can be used to view the specific syntax and description in this way , Therefore, there is no need to deliberately remember the specific details of these data types , Remember and forget , Learning how to check is more meaningful than this .
Next, I will explain several commonly used data types .
1. value type
1 Bytes =8 Bit binary ,8 position =2^8=256, therefore 1 Total length of bytes =256
1111 1111=255, therefore 1 The maximum stored value of bytes is 255
among “0000 0000”=0 It's also a value ,1+255=256=2^8
So you know 1 Total length of bytes and Storing maximum values is not the same concept !!! Total length = Maximum +1
Unsigned maximum calculation formula :n byte =(2^n*8)-1

Both integer and point types can be constrained :[UNSIGNED] [ZEROFILL] Namely “ Unsigned ” and “ Zero compensation ”.
Integer and point type syntax : Basic grammar [UNSIGNED] [ZEROFILL] UNSIGNED Only non negative numbers can be stored ZEROFILL Automatically add zero in front of the stored value to fill the remaining digits , And automatically add UNSIGNED attribute
1.1 Examples of integer types
How to choose ? The main Look at the effective range Whether it meets the business requirements
-- int type , Unsigned , Not empty , Auto increment
CREATE TABLE animals (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name CHAR(30) NOT NULL,
PRIMARY KEY (id)
);
-- Insert multiple data , No need to give id assignment
INSERT INTO animals (name)
VALUES
('dog'),('cat'),('penguin'),('lax'),('whale'),('ostrich');
For general automatic increment ,int unsigned Can be stored 42 More than 100 million pieces of data , It's enough to use , No need to use bigint type . Use bigint Type means , The primary key of each data Need to use more than twice as much space and more computing resources .
1.2 Examples of point types
create table t1( id1 float(9,2), id2 double(9,2), id3 decimal(9,2));It can be seen that the grammar is the same

insert into t1 values('1.2','1.24','1.235');Meeting Automatically add decimal places 、 Beyond the decimal places rounding

among DECIMAL All basic calculations of columns (+、-、*、/) Are subject to 65 The accuracy of digits is completed . For storage Amount type , Be sure to use decimal Type to store .DECIMAL The maximum range is :DECIMAL(65,30).
2. Character type

char Characteristics :
Save fixed length M
The saved value is greater than M Will be cut off , Less than will be filled with spaces
Maximum character length 255
varchar Characteristics :
Only store the actual length of the string
Use extra 1~2 Bytes to store the length of the value (0~255 Use 1 byte , otherwise 2 byte )
Maximum character length 65535
Key points
char and varchar The length of refers to “ Character length ”, Instead of byte length , Different encoding requires different byte lengths
latin1 Occupy 1 Bytes ,gbk Occupy 2 Bytes ,utf8 Occupy 3 Bytes ,utf8mb4 Occupy 4 Bytes
When using gbk When coding ,char The maximum character length is 255;varchar Maximum character length 32766
When using utf8 When coding ,char The maximum character length is 255;varchar Maximum character length 21844
When using utf8mb4 When coding ,char The maximum character length is 255;varchar Maximum character length 16383
Example :
Such as :char(3), Fixed storage of three characters , Different codes Required for fixing Number of bytes :latin1 need 3 Bytes ,gbk need 6 Bytes ,utf8 need 9 Bytes .
Such as :varchar(3), Store up to three characters , Different codes Maximum required Number of bytes :latin1 need 4 Bytes ,gbk need 7 Bytes ,utf8 need 10 Bytes .
Such as :varchar(256), Maximum storage 256 Characters , Different codes Maximum required Number of bytes :latin1 need 258 Bytes ,gbk need 514 Bytes ,utf8 need 770 Bytes .
-- grammar
CHAR[(M)] [CHARACTER SET charset_name] [COLLATE collation_name]
VARCHAR(M) [CHARACTER SET charset_name] [COLLATE collation_name]
-- Or you could write it as
CHAR[(M)] [CHARSET charset_name] [COLLATE collation_name]
VARCHAR(M) [CHARSET charset_name] [COLLATE collation_name]How to choose char and varchar
Fixed length option char, Not affected by coding . Such as :uuid character string ,md3 character string ;
Choose one that often changes length varchar. Such as : Home address , Personal profile .
3. Time type

3.1 timestamp and datetime
See the examples in the table for the specific format of time type , among timestamp and datetime Can be accurate to seconds
Example


timestamp By default, it will be automatically updated to the current time ,datetime The default is empty. null, But you can specify the default value when you see the table , Make both the same default .
-- CURRENT_TIMESTAMP Insert the default current time
-- on update CURRENT_TIMESTAMP The default time when updating
create table time2(
id int,
ts timestamp,
dt datetime default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP
);
timestamp and datetime difference
The number of bytes required is different ,timestamp 4 Bytes ,datetime 8 Bytes
The effective range is different ,timestamp Maximum 2038 year ,datetime 9999 year
MySQL How to represent the current time in ?
In addition to the default values mentioned above CURRENT_TIMESTAMP
There are also the following
CURRENT_TIMESTAMP()
NOW()
LOCALTIME
LOCALTIME()
LOCALTIMESTAMP
LOCALTIMESTAMP()

Remember which one is simple , Remember function now() Just fine , Others look familiar .
3.2 date and time
There's nothing to talk about , Just remember the data format , See the table above for details
Look at an example

3.3 year
Year fixed 4 position , Let's look at an example
create table year1 ( id int,y year );insert into year1 (id,y) values (1,now()),(2,2022-12-30),(3,2022),(4,22);
Follow official account for free PDF E-books and read more related articles

边栏推荐
- View CSDN personal resource download details
- 按键精灵跑商学习-商品数量、价格提醒、判断背包
- Doris / Clickhouse / Hudi, a phased summary in June
- uniapp---初步使用websocket(长链接实现)
- Latex error: missing delimiter (. Inserted) {\xi \left( {p,{p_q}} \right)} \right|}}
- BGP advanced experiment
- Baidu R & D suffered Waterloo on three sides: I was stunned by the interviewer's set of combination punches on the spot
- System.currentTimeMillis() 和 System.nanoTime() 哪个更快?别用错了!
- RHCE day 3
- Exercise 7-3 store the numbers in the array in reverse order (20 points)
猜你喜欢
What are the advantages of automation?

【OpenCV 例程200篇】218. 多行倾斜文字水印

uniapp 处理过去时间对比现在时间的时间差 如刚刚、几分钟前,几小时前,几个月前

Latex learning insertion number - list of filled dots, bars, numbers

Hands on deep learning (41) -- Deep recurrent neural network (deep RNN)

Doris / Clickhouse / Hudi, a phased summary in June

Hands on deep learning (42) -- bi-directional recurrent neural network (BI RNN)

Architecture introduction

How can Huawei online match improve the success rate of player matching

Custom type: structure, enumeration, union
随机推荐
Exercise 9-3 plane vector addition (15 points)
Architecture introduction
Pcl:: fromrosmsg alarm failed to find match for field 'intensity'
Exercise 9-5 address book sorting (20 points)
Reasons and solutions for the 8-hour difference in mongodb data date display
Check 15 developer tools of Alibaba
leetcode729. My schedule 1
Exercise 7-8 converting strings to decimal integers (15 points)
Talk about scalability
对于程序员来说,伤害力度最大的话。。。
libmysqlclient. so. 20: cannot open shared object file: No such file or directory
Rhcsa12
Golang type comparison
Lavel document reading notes -how to use @auth and @guest directives in lavel
按键精灵打怪学习-识别所在地图、跑图、进入帮派识别NPC
Number of relationship models
Latex error: missing delimiter (. Inserted) {\xi \left( {p,{p_q}} \right)} \right|}}
Legion is a network penetration tool
Application of safety monitoring in zhizhilu Denggan reservoir area
按键精灵跑商学习-商品数量、价格提醒、判断背包