Detailed explanation of the type definition of Mysql column - the most detailed tutorial in history (including actual combat)

Table of contents

foreword

1. Plastic type

1. Incidental attributes of integer types

(1). Parentheses after the type name

(2).unsigned

(3).auto_increment

2. Floating-point and fixed-point types

1. Type table

2. The difference between the three types

(1). Difference

(2).Advice

3. Character type

1.CHAR type and VARCHAR type

(1). String character (M)

(2). Actual combat type

2. Text type

(1). Type table

(2). Special attention

(3). Practical suggestions

(4). Practical exercises

3. ENUM and SET types

(1). ENUM type

(2).SET type

4. Date and event type

1. Type table

2. Type introduction

Five, binary type

1. Type table     

2. Type

(1). BINARY and VARBINARY

(2).BIT type

(3) BLOB type

3. Practical suggestions

Summarize


✨✨✨Hello everyone, I am Flying Fish-blog. Today I will introduce Mysql to you. If there are any shortcomings, please give me your advice. Thank you for your support! ! !

 

foreword

1) It is composed of 26 letters and natural numbers from 0 to 9 plus the upper and lower '_'. The naming is concise and clear. Multiple words are separated by an underscore '_'

2) All lowercase names, try to avoid uppercase

3) The field must be filled with description information

4) Prohibit the use of database keywords

5) Field names generally use nouns or verb-object phrases

6) The name of the field used must be easy to understand, generally no more than three English words

7) When naming the columns of the table, do not repeat the name of the table (for example: in the user table, the user_name field appears)

8) Field naming uses the full name

        

1. Plastic type

        The integer type is the most basic data type in the database. The two data types INTEGER and SMALLINT are supported in standard SQL. In addition to supporting these two types, the MySQL database also supports TINYINT, MEDIUMINT, and BIGINT. The following table compares the number of bytes and value ranges of different integer types.

mysql> use school;   #选择数据库school

mysql> create table class5(class_id int , class_name varchar(128), class_teacher varchar(64) );         #创建表class5

1. Incidental attributes of integer types

(1). Parentheses after the type name

        Specifies the display width (not the number of bytes this type occupies). Defaults to tinyint(3), smallint(5), mediumint(8), int(11) and bigint(20) if width is not explicitly specified. It is generally used with zerofill. As the name suggests, zerofill means to fill with "0", that is, to fill the space where the number of digits is not enough with the character "0".

mysql> use school;   #选择数据库school

mysql> create table class6(class_id integer(5) zerofill, class_name varchar(128), class_teacher varchar(64) );         #创建表class6

(2).unsigned

         If you need to save a non-negative number in the field or need a large upper limit, you can use this option. Its value range is that the lower limit of the normal value is 0, and the upper limit is twice the original value. For example, tinyint signed range It is -128~+127, while the unsigned range is 0~255. If a column is specified as zerofill, MySQL automatically adds the UNSIGNED attribute to the column.

mysql> use school;   #选择数据库school

mysql> create table class6(id integer unsigned , name varchar(128), teacher varchar(64) );         #创建表class6

mysql> create table class7(id integer zerofill , name varchar(128), teacher varchar(64) );         #创建表class7, id类型为 int unsigned

(3).auto_increment

        This attribute can be used when a unique identifier or sequence value needs to be generated. This attribute is only used for integer types. AUTO_INCREMENT values ​​generally start at 1 and increase by 1 for each row. There can be at most one AUTO_INCREMENT column in a table. For any column that wants to use AUTO_INCREMENT, it should be defined as NOT NULL and either defined as a PRIMARY KEY or defined as a UNIQUE key. For example, an AUTO_INCREMENT column can be defined in any of the following ways:

mysql> use school;   #选择数据库school

mysql> create table class8(id integer auto_increment PRIMARY KEY , name varchar(128), teacher varchar(64) );         #创建表class8, id 具有自增长属性

mysql> create table class9(id integer auto_increment UNIQUE , name varchar(128), teacher varchar(64) );         #创建表class9, id 具有自增长属性

2. Floating-point and fixed-point types

        Decimals are represented by floating-point and fixed-point types in data tables. The types of floating-point numbers include single-precision floating-point numbers (FLOAT type) and double-precision floating-point numbers (DOUBLE type). The fixed-point type is the DECIMAL type. The following is a comparison of the number of bytes and value ranges of these three types, as shown in the table below.

1. Type table

 

2. The difference between the three types

(1). Difference

        The float value type is used to represent single-precision floating-point values, while the double value type is used to represent double-precision floating-point values. Both float and double are floating-point types, and decimal is a fixed-point type;

mysql> use school;   #选择数据库school

mysql> create table class10 (f1 float, do1 double, de1 decimal);  #创建表class10

        MySQL floating-point and fixed-point types can be represented by adding (M, D) after the type name. M represents the total length of the value, and D represents the length after the decimal point. M and D are also called precision and scale, such as float( 7,4) can be displayed as -999.9999, and MySQL will round up the value when saving the value. If 999.00009 is inserted, the result will be 999.0001. For decimal, M is the maximum number of digits (precision), ranging from 1 to 65. Can not be specified, the default value is 10. D is the number of digits (decimal places) to the right of the decimal point. The range is from 0 to 30, and cannot be greater than M. It can be left unspecified, and the default value is 0.

        When FLOAT and DOUBLE do not specify the precision, they will be displayed according to the actual precision by default. When DECIMAL does not specify the precision, the default integer is 10 and the decimal is 0, that is (10, 0).

(2).Advice

        When we need to store decimals and have precision requirements, such as storing amounts, we usually consider using the DECIMAL field type!!!

3. Character type

1.CHAR type and VARCHAR type

        Both the CHAR type and the VARCHAR type specify the maximum length when creating a table, and their basic forms are as follows:

(1). String character (M)

        Among them, the "string type" parameter specifies whether the data type is CHAR or VARCHAR; the M parameter specifies that the maximum length of the string is M. For example, CHAR(4) means that the data type is CHAR type, and its maximum length is 4.

        The length of the CHAR type is fixed and is specified when the table is created. Its length can be any value from 0 to 255. For example, CHAR(100) specifies that the length of the CHAR type is 100. When CHAR stores values, they are right-padded with spaces to the specified length.

        The length of the VARCHAR type is variable, and the maximum length is specified when creating the table. When defined, its maximum value can take any value between 0 and 65535. After specifying the maximum value of the VARCHAR type, its length can be between 0 and the maximum length. For example, the maximum length of VARCHAR(100) is 100, but not every record occupies 100 bytes, but allocates as much as it uses within the maximum range. The actual space occupied by the VARCHAR type is the actual length of the string plus 1 or 2, which can effectively save system space.
 

value

CHAR(4)

storage bytes

VARCHAR(4)

storage bytes

‘’

‘’

4

‘’

1

‘ab’

‘ab’

4

‘ab’

3

‘abcd’

‘abcd’

4

‘abcd’

5

‘abcdefgh’

-

#Insert failed

-

#Insert failed


mysql> use test;   #选择数据库test

mysql> create table char_example(e_char char(5), v_char varchar(5)); #创建数据库表

mysql> insert into char_example values('12345','12345');  #正常插入数据

mysql> insert into char_example values('1 2  ','1 2  ');   #char类型会屏蔽后面隐藏的空格,varchar 不会

mysql>select concat('(',e_char, ')'), concat('(',v_char, ')')  from char_example ; #让char 后面屏蔽的空格原型毕露

(2). Actual combat type

1. Char will definitely use the specified space, and varchar determines the space according to the data.
2. The data query efficiency of char is higher than that of varchar: varchar needs to be calculated by the number of records behind.
3. If it is determined that the data must occupy the specified length, then Use char type;
4. If you are not sure how much data there is, then use varchar type;
5. If the data length exceeds 255 characters but is within 65535, use varchar directly
. 6. If you want to keep spaces at the end of the string, you must choose varchar

2. Text type

(1). Type table

         The TEXT type is a special string type, including TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT. The comparison of its length and storage space is shown in the following table:

         The difference between various TEXT types lies in the allowed length and storage space. Therefore, among these several TEXT types, select the type that can meet the needs and save space according to the needs.

(2). Special attention

1) The above types do not need to specify the length!

2) The allowed length refers to the actual number of bytes stored, not the actual number of characters. For example, if a Chinese character occupies two bytes, then the TEXT type can store 65535/2 = 32767 Chinese characters, and varchar( 100) It can store 100 Chinese characters, which actually occupies 200 bytes, but varchar(65535) cannot store 65535 Chinese characters, because it has exceeded the expression range.

mysql> use test;   #选择数据库test

mysql> create table text_example(e_text tinytext, v_char varchar(255)); #创建数据库表,e_text 可存储255个字节,v_char可存储255个字符  


mysql> insert into char_example values(90个中文字符,90个中文字符);  #插入失败,utfmb4 用3个字节表示一个中文汉字,会超出tinytext 保存范围


mysql> insert into char_example values(80个中文字符,100个中文字符);  #插入成功   

(3). Practical suggestions

  • 1. The length of char is fixed, that is, each piece of data occupies the same length of byte space; it is suitable for ID card numbers, mobile phone numbers, etc. More than 255 bytes can only use varchar or text;
  • 2. Varchar has a variable length, and the maximum length can be set; it is suitable for attributes with variable length.
  • 3. Text does not set the length. When the maximum length of the attribute is not known, it is suitable to use text. Where varchar can be used, text is not used;
  • 4. If you can choose, according to the query speed: char is the fastest, followed by varchar, and text is the slowest.

(4). Practical exercises

        Create a user information table to store the following information of the user: name, mobile phone number, home address, personal profile, gender, age, ID number. The database table name can be defined as userinfo, and at the same time, add a column id as the unique identifier of each record, and set it as the primary key, self-added!

mysql> use test;   #选择数据库test

mysql> create table userinfo (

 id int(11) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT COMMENT ‘主键’,

 name   varchar(64) DEFAULT NULL COMMENT ‘姓名’,

 mobile  char(11)  DEFAULT NULL COMMENT ‘手机号码’,

 address varchar(128) DEFAULT NULL COMMENT ‘居住地址’,

 description text  DEFAULT NULL COMMENT ‘个人简介-不知道具体的范围,不常更新用text’,

 sex     char(1)  DEFAULT NULL COMMENT ‘性别 - 男或女’,

 age     tinyint unsigned DEFAULT 0 COMMENT ‘年龄’,

 idno    char(18) DEFAULT NULL COMENT ‘身份证号码’

);  

3. ENUM and SET types

(1). ENUM type

        The ENUM type is also called an enumerated type. When creating a table, the value range of the ENUM type is specified in the form of a list, and its basic form is as follows:

Attribute name ENUM('value1', 'value2', ..., 'valuen')

        Among them, the "attribute name" parameter refers to the name of the field, and the "value n" parameter indicates the nth value in the list. The value of ENUM type can only take one element in the list. There can be up to 65535 values ​​in its value list. If the data value list is within 255, then one byte is enough. If it exceeds 255 but less than 65535, then the system uses two bytes to save. Each value in the list has a unique serial number, which is stored in MySQL instead of the value in the list. Default numbering starts from 1!

Enum('Male','Female','Choose to keep secret') # 'Male'=>1 'Female'=>2 'Choose to keep secret'=> 3

mysql> use test;   #选择数据库test

mysql> create table enum_example (e_enum enum('男','女','选择保密') ); #创建表

mysql> insert into enum_example values('男');  #插入记录,必须是enum 选项中的值

mysql> insert into enum_example values(1);  #插入记录可以用数值表示

mysql>select e_enum + 0  from enum_example; #查询enum 选项对应的整数值

        If the ENUM type is added with the NOT NULL attribute, its default value is the first element of the value list. If the NOT NULL attribute is not added, the ENUM type will allow NULL to be inserted, and NULL is the default value.

(2).SET type

        When creating a table, the value range of the SET type is specified in the form of a list, and its basic form is as follows:

  Attribute name SET('value1', 'value2', ..., 'valuen')

        Among them, the attribute name parameter refers to the name of the field, and the "value n" parameter indicates the nth value in the list. The spaces at the end of these values ​​will be directly deleted by the system. Its basic form is the same as the ENUM type. The value of the SET type can take one element or a combination of multiple elements in the list. When taking multiple elements, separate them with commas. The value of the SET type can only be a combination of up to 64 elements.

mysql> use test;   #选择数据库test

mysql> create table set_example (interest set('足球','追剧','篮球','撩妹') ); #创建表

mysql> insert into set_example values( '足球,撩妹' ); #插入记录,必须是enum 选项中的值

mysql> insert into enum_example values(9);  #插入相应位效果等同,9 =>1001 选择1,4

mysql>select interest+0 from set_example;  #以整数的方式查询

4. Date and event type

        The date and time type is designed for convenient storage of date and time in the database, and the database has multiple data types representing date and time. Among them, the YEAR type represents the year, the DATE type represents the date, the TIME type represents the time, and the DATETIME and TIMESTAMP represent the date and time.

1. Type table

        The following is a comparison of the byte count, value range, and zero value of these five date and time types, as shown in the table below.

 

2. Type introduction

        Each date and time type has a valid range. If the value inserted exceeds this range, the system will report an error and insert a zero value into the database. Different date and time types have different zero values.

        When inserting the date and time, the date year, month, day and time hour, minute, and second can be separated by any character in " : - _ /  ". If the time is inserted alone, an error will be reported! ! !

mysql> use test;   #选择数据库test

mysql> create table date_example (e_date date, e_datetime datetime, e_timestamp

 timestamp, e_time time, e_year year);  #创建表dt_example

mysql> insert into date_example values('2020-5-9', '2020-5-9 15:01:00', '2020-05-09 15:01:00', '15:56:01', 2011);

mysql> insert into date_example values('2020_5/9', '2020:5-9 15/01-00', '2020:05/09 15-01_00',  '15:56:01', '2011');   #效果同上面插入语句

It can also be obtained through the time function provided by mysql itself:

Commonly used time functions:

        CURDATE() - Get the current DATE, which can be directly inserted into the DATE type.

        NOW() - Get the current DATETIME, which can be directly inserted into DATETIME and TIMESTAMP types.

        TIME() - Get the hour, minute, and second in the time string given by the parameter, which can be directly inserted into the TIME type.

        YEAR() - Get the year in the time string given by the parameter, which can be directly inserted into the YEAR type.

        MONTH() , DAY() , HOUR() , MINUTE() , SECOND() Get the month, day, hour, minute, second value in the time string given by the parameter.

mysql> use test;   #选择数据库test

mysql> insert into date_example values(CURDATE(), NOW(), NOW(), time(NOW()), YEAR(NOW()) );

Five, binary type

        The biggest difference between binary data and text data in mysql is:

The binary type stores raw binary data (such as pictures, videos, exe files, etc.). The text type (TEXT) is used to store character strings (such as strings composed of English characters, Chinese characters, or other language characters).
        Binary types have no character set, and sorting and comparisons are based on the numeric values ​​of the column value bytes. The TEXT type has a character set, and the values ​​are sorted and compared according to the collation rules of the character set.

1. Type table     

        Binary types are data types that store binary data, including BINARY, VARBINARY, BIT, TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB. The comparison between binary types is shown in the table below.

2. Type

(1). BINARY and VARBINARY

        Both the BINARY type and the VARBINARY type specify the maximum length when creating a table, and their basic forms are as follows:

Type (M) 

        Among them, the "string type" parameter specifies whether the data type is BINARY or VARBINARY; the M parameter specifies that the maximum byte length of the binary number is M. This is similar to the CHAR and VARCHAR types. For example, BINARY(10) means that the data type is BINARY type, and its maximum length is 10.

  1. The length of the BINARY type is fixed, and it is specified when creating the table, and the space that is less than the maximum length is filled with "\0". For example, BINARY(50) specifies that the length of the BINARY type is 50.

     The length of the VARBINARY type is variable, and the maximum length is specified when the table is created. Its length can be between 0 and the maximum length, and it can be allocated as much as it is used within the maximum range.

mysql> use test;   #选择数据库test

mysql> create table bin_example(e_bin  binary(5),e_varbin varbinary(5)); #创建表

mysql> insert into bin_example values( 'ab','ab'); #插入记录,可以是普通字符串

mysql> insert into bin_example values( b'0110000101100010',b'0110000101100010'); #插入记录,可以是二进制,与上例等同

mysql> select * from bit_example ;  #以十六进制的方式显示

(2).BIT type

        Among them, "M" specifies that the maximum storage length of the binary number is M, and the maximum value of M is 64. For example, BIT(4) means that the data type is BIT type and the length is 4. If the data stored in the field type BIT(4) is 0~15, since the value of 15 is 1111 after being converted into binary, its length is 4. If the inserted value is 16, its binary number is 10000, and its length is 5, which exceeds the maximum length. Therefore, a number greater than 16 cannot be inserted into a BIT(4) type field.

Operation points:

  1. When inserting data, use b'bit string' to insert the corresponding value!
  2. When querying, you can use the bin(), oct(), and hex() functions to convert the value of the field into the corresponding binary, octal, and hexadecimal.
mysql> use test;   #选择数据库test

mysql> create table bit_example (b bit(8) ); #创建表

mysql> insert into bit_example values( b'10110111' ); #插入记录,可以是二进制位

mysql> insert into bit_example values( 'a' ); #插入记录,可以是字符,但不能超出字节长度

mysql> select bin(b) from bit_example ;  #以二进制的方式显示字段值

(3) BLOB type

1. The above types do not need to specify the length!

2. The allowed length refers to the actual number of bytes stored, regardless of character encoding.

3. Practical suggestions

  • 1. The binary length is fixed, that is, each piece of data occupies the same length of byte space; the binary data whose length does not exceed 255 bytes is saved;
  • 2, varbinary variable length, you can set the maximum length, the maximum length is 65535; suitable for binary data with variable length;
  • 3. The length of the blob is not set. When the maximum length of the attribute is not known, it is suitable to use the blob. Where varbinary can be used, the blob is not used;
  • 4. If you can choose, according to the query speed: binary is the fastest, followed by varbinary, and blob is the slowest.

Summarize

✨✨✨The above is the summary of my study. I hope everyone will discuss, discuss, and work together to move towards a better tomorrow! ! !

Guess you like

Origin blog.csdn.net/m0_65635427/article/details/130295628