[MySQL]Data type of database

1. Data type classification

The data types in mysql are classified as follows, among which the types in red font are commonly used types:

Insert image description here

2. Numeric type

Insert image description here

The establishment attribute column of the table in mysql列名称 数据类型 : , for example num int, it is inverted with the language data type we usually write!

1. tinyint

Next, we create a table with only tinyint type, and then insert 1 and 128 respectively. We will find that the insertion of 128 fails because it is inserted out of bounds and exceeds the type range:

Insert image description here

illustrate:

  • In MySQL , integers can be specified as signed or unsigned, and the default is signed;
  • You can use unsigned to indicate that a field is unsigned;

For example, in the example below, if we create an unsigned table, inserting -1 will fail because the unsigned range of tinyint is 0~255 :

Insert image description here

You can deduce other types by yourself. Note: Try not to use unsigned . For data that may not be stored in the int type, int unsigned may also not be able to be stored. Instead of this, it is better to upgrade the int type to the bigint type during design .

2. bit

Basic syntax: bit[(M)]: bit field type. M represents the number of bits per value, ranging from 1 to 64. If M is omitted, it defaults to 1.

Next we create a t3 table with data types of int and eight bits :create table t3(id int, a bit(8));

Next insert a number 1 and observe:

Insert image description here

We found that nothing appears in data 1 of a. In fact, when the bit field is displayed, it is displayed according to the value corresponding to the ASCII code . For example, if we insert 65, its corresponding ASCII code value bit 'A' :

Insert image description here

If we have such a value that only stores 0 or 1, such as gender, only male and female, then we can define bit(1) , which can save space:

Insert image description here

As shown in the figure above, when inserting 2, it has been inserted out of bounds, because there is only one bit , only 0 and 1.

3. Decimal type

(1)float

Syntax: float[(m, d)] [unsigned]: m specifies the display length, d specifies the number of decimal places, and occupies 4 bytes of space.

For example, decimals: The range represented by float(4,2) is -99.99 ~ 99.99 . MySQL will round off the value when saving it. For example:

Insert image description here

As above -99.992, the last digit is rounded to -99.99. Insert:

Insert image description here

If float(4,2) unsigned is defined, because it is specified as an unsigned number, the range is 0 ~ 99.99.

(2)decimal

Syntax: decimal(m, d) [unsigned]: The fixed-point number m specifies the length, and d represents the number of decimal points.

For example:

  • The range represented by decimal(5,2) is -999.99 ~ 999.99
  • decimal(5,2) unsigned represents the range 0 ~ 999.99

Note: decimal is very similar to float, but there is a difference: float and decimal represent different precisions.

For example, we create a table:create table t6 (id int, salary1 float(10, 8), salary2 decimal(10, 8));

Insert the data again and view the data:

Insert image description here

As shown in the figure above, it is found that the accuracy of decimal is more accurate, so if we want a certain data to represent high precision, we can choose decimal.

Note: The precision represented by float is approximately 7 digits; the maximum number of decimal integer digits m is 65; the maximum number of supported decimal digits d is 30 ; if d is omitted, the default is 0 ; if m is omitted, the default is 10.

3. String type

1. char

Syntax: char(L): fixed-length string, L is the length that can be stored, the unit is characters, the maximum length value can be 255.

For example, we first create a table:create table t7 (id int, name char(2));

Insert data again:

Insert image description here

View data:

Insert image description here

Note: char(2) means that it can store two characters, which can be letters or Chinese characters, but cannot exceed 2. char(255) can only be 255 at most.

If we insert data larger than two characters into the above table, as shown below, it will be inserted out of bounds:

Insert image description here

This also illustrates a problem. If we insert illegal data into a specific type of mysql , mysql will usually directly intercept us and prevent us from performing corresponding operations! On the other hand, if we have successfully inserted data into mysql , the insertion must be legal! Therefore, in MySQL , generally speaking, the data type itself is also a constraint. The so-called constraint is to force the user to insert as correctly as possible. The user is constrained, so as to ensure that the data in the database is predictable and complete. of.

2. varchar

Syntax: varchar(L): variable length string, L represents the character length, the maximum length is 65535 bytes.

For example: create table t8 (id int, name varchar(6));it means that name can store 6 characters, and the inserted data is as follows:

Insert image description here

Note: Regarding varchar(len), how big is len? This len value is closely related to the encoding of the table:

  • The length of varchar can be specified as a value between 0 and 65535, but there are 1 - 3 bytes used to record the data size, so the effective number of bytes is 65532;
  • When the encoding of our table is utf8, the maximum value of parameter n of varchar(n) is 65532/3=21844 (because in utf, one character occupies 3 bytes), if the encoding is gbk, the parameter n of varchar(n) The maximum n is 65532/2=32766 (because in gbk, one character occupies 2 bytes);

We can verify that we can create a table containing the varchar type and set the size to 21844, because the character set defaults to utf8 , as follows:

Insert image description here

The above figure verifies that utf8 cannot exceed 21844.

We can check the character set of the current table again by using the command: show create table t8\Gwhere \Grepresents the row display:

Insert image description here

3. Comparison between varchar and char

For example, there are two types: char(4) and varchar(4) :

  • When we store 'abcd', char(4) occupies 4*3=12 bytes; varchar(4) occupies 4 * 3 + 1 = 13 bytes;
  • When we store 'A', char(4) occupies 4*3=12 bytes; varchar(4) occupies 1 * 3 + 1 = 4 bytes;
  • They both throw errors when we store 'Abcde'.

So how do we choose fixed-length or variable-length strings?

  1. If the data length is determined to be the same, use fixed length (char), such as: ID card, mobile phone number, md5;
  2. If the data length changes, use variable length (varchar), such as name, address, but you have to ensure that the longest one can be stored;
  3. Fixed-length disk space is wasteful, but efficient;
  4. Variable-length disk space saves more space, but is less efficient;
  5. The meaning of fixed length is to directly open up the corresponding space;
  6. The meaning of variable length is to use as much as possible without exceeding the custom range.

4. Date and time types

There are three commonly used dates:

  • date: date 'yyyy-mm-dd', occupies three bytes;
  • datetime time date format 'yyyy-mm-dd HH:ii:ss' represents the range from 1000 to 9999, occupying eight bytes;
  • timestamp: timestamp, starting from 1970, the yyyy-mm-dd HH:ii:ss format is exactly the same as datetime, occupying four bytes.

Next create the table:create table birthday (t1 date, t2 datetime, t3 timestamp);

Insert data: insert into birthday(t1,t2) values('2000-1-1','2000-1-1 01:1:1');This insertion method is to insert specified columns. We used to use full column insertion, that is, all columns are inserted by default. We will talk about this later; the results are as follows:

Insert image description here

Next we try to update the data:update birthday set t1='2000-2-2';

Insert image description here

From the above figure, when the data is updated, the timestamp in column t3 will be updated to the current time.

5. enum and set

  • enum syntax:

      	enum:枚举,“单选”类型;
      	enum('选项1','选项2','选项3',...);
    

This setting only provides the values ​​of several options. In the end, only one of the values ​​is actually stored in a cell; and for efficiency reasons, these values ​​are actually stored as "numbers" because the value of each option of these options Corresponding to the following numbers in turn: 1, 2, 3,... up to 65535; when we add enumeration values, we can also add corresponding numbers.

  • set syntax:

      	set:集合,“多选”类型;
      	set('选项值1','选项值2','选项值3', ...);
    

This setting only provides the values ​​​​of several options. In the end, the design can store any number of values ​​​​in one cell; and for efficiency reasons, these values ​​​​are actually stored as "numbers", because each of these options The option values ​​correspond to the following numbers in sequence: 1, 2, 4, 8, 16, 32, ... up to 64.

Note: It is not recommended to use numbers when adding enumeration values ​​and set values, because it is not conducive to reading.

For example, there is a questionnaire votes that needs to investigate people's preferences, such as (reading, swimming, basketball, football) to choose (multiple choices are allowed), (male, female) [single choice]:

		mysql> create table votes(
		    -> name varchar(20),
		    -> hobby set('看书', '游泳', '篮球', '足球'),
		    -> gender enum('男', '女')
		    -> );

Insert data and view the data:

Insert image description here

We can view the data in the table based on the specified information. Suppose we insert some more data:

Insert image description here

Suppose we need to filter out information whose gender is female, we can use the statement:select * from votes where gender=2;

Insert image description here

Suppose we continue to add data as follows:

Insert image description here

Note that the syntax for inserting multiple hobbies is as follows: insert into votes values('Jack', '篮球,看书', 2);Note that when multiple hobbies are separated by commas, do not use spaces to separate them.

Suppose we need to filter out all names with basketball hobbies , we can:

Insert image description here

As shown in the picture above, it is not the result we want, because Smith and Jack 's hobby also has basketball options, so we need to use a set query. The set query uses the find_ in_ set function.

find_in_set(sub, str_list): If sub is in str_list, return the subscript; if not, return 0; str_list is a comma-separated string.

Use for example:

Insert image description here

Insert image description here

Below we use find_in_set to filter out all names with basketball options in hobby :select * from votes where find_in_set('篮球', hobby);

Insert image description here

Supongo que te gusta

Origin blog.csdn.net/YoungMLet/article/details/135004006
Recomendado
Clasificación