[MySQL] table operations and data types

foreword

        Hello everyone~, continue our mysql learning today!

        This blog mainly records that after Mysql creates a database, to create a table in the database, you first need to define the structural constraints (SQL-DDL) of the table, etc. This article mainly introduces the structure of the basic definition table (create, delete, modify, search ) and learning of some data types.

My last MySQL note: [MySQL] library operation

Table of contents

1. Table structure operation - DDL

1. Create a table

2. Lookup table

- Find all tables in the current database

-View table structure

- View table creation statement

3. Modify table

- Modify column names

- Modify the table name

4. Delete table

2. Data type

1. Numeric type

- integer type

-bit type

- Decimal type

2. Text type

3. Date time type

4. enum and set types

find_in_set()


1. Table structure operation - DDL

1. Create a table

        First, the format of the sql statement to create the table is as follows:

create table [if not exists] table_name(

        filed1 datatype,

        filed2 datatype,

        ......

)engine storage engine charset(character set character set)=character set collate=check rule;

Notice:

        The content behind () is mandatory , but according to the settings on the mysql software layer, it can be omitted, because it can completely inherit the attributes of creating a database in the current environment or the attributes of the default settings.

        Storage engine : It is the third layer mentioned in the MySQL architecture. There are different storage methods for different engines, as you can see in the following experiments. (such as MyISAM engine and InnoDB engine)

        filed  is the column attribute name. Note that all self-defined variable names can be enclosed in `-backticks.

        datatype data type, constraints, and so on. (I will talk about it later, the following knowledge is an example)

        The following is just an example. We need a table to store user id, account number, and password. Please create its structure. The storage engine is MyISAM. At the same time, create the same table with the storage type as InnoDB.

create table `User1`(
    `nm` int(3) zerofill comment '用户num',
    `id` char(5) comment '用户id固定为5个长度',
    `pw` char(7) comment '用户密码固定7个长度'
)engine MyISAM default charset=utf8;

create table `User2`(
    `nm` int(3) zerofill comment '用户num',
    `id` char(5) comment '用户id固定为5个长度',
    `pw` char(7) comment '用户密码固定7个长度'
)engine InnoDB character set utf8 collate utf8_bin;

         It can be found that because of the difference in storage engines, the storage methods of data files are also different. (Mysql default path to save data files is /var/lib/mysql)

        So now that the table structure is created, how do we find our table structure or table?

2. Lookup table

- Find all tables in the current database

show tables;

-View table structure

desc table name ;

- View table creation statement

show create table table name[\G]

\G In order to organize the format for easy viewing

        It can be found that the comment constraint we set before can be seen, and this constraint setting is for programmers to see.

        At this point the structure of the table is fixed. But what if we need to change some attributes halfway? Just use the keyword alter.

3. Modify table

        There are also three types of modification table structures:

alter table How to change table name (attribute name [datatype,...]) [after attribute name]

explain:

        How to divide into three categories:

        Add is added, followed by the attribute name and the type and constraints for it, and after means that the added attribute is behind the specified attribute.

        drop to delete, just follow the attribute name.

        modify modification, followed by attributes and corresponding types and constraints.

Notice:

        - If there is data in the current table, there may be problems, so the structure of the table must be thought out in advance, and it is necessary to modify the structure of the table.

        - When modifying operations, they are all overwriting operations, so the constraints must be written completely.

        - When deleting an attribute, all data in the current column will also be deleted, so think twice.

        -Delete When there is only one column left, you cannot perform the delete attribute operation, but delete the table operation. (A table structure has at least one attribute)

        The three modification operations are demonstrated below, together with precautions. 

        First, we add and modify the structure of the table User1, and add the name attribute to the back of the id.

alter table User1 add name varchar(10) after id;

         Second, we modify the id attribute to int(5) data type.

alter table User1 modify id int(5);

         Then delete the line nm.

alter table User1 drop nm;

         Now test to delete all the columns of the User2 table (is it deleted?)

alter table User2 drop nm;
alter table User2 drop id;
alter table User2 drop pw;

         It can be found that when there is only one column left in the table, the attribute cannot be deleted directly, and the table needs to be deleted together, otherwise the table without attributes is meaningless.

- Modify column names

        Modifying column names is easy:

        alter table table name change oldname newname (datatype....)  // Constraints, etc.

        Note that modifying column names is also an overwriting operation.

        For example, we modify the id of the table User1 to ID:

         It should be noted that because it is an overlay modification, the originally created data type and constraint type must also remain intact as before.

- Modify the table name

        The database omits the operation of modifying the database name, but the name of the table can be modified.

       alter table old table name rename new table name (to new table name) ;

        For example, we modify the User2 table to the Temp table.

4. Delete table

        To delete a table, use the keyword drop.

        drop table table name 1[, table name 2...];

Note: You also need to think twice about deleting tables.

        For example, we delete the table Temp:

         Correspondingly, all data files created before will also be cleaned up.

2. Data type

The data type is a constraint         when creating table attributes . Data types in MySQL are roughly divided into four categories, and are designed according to different application scenarios.

        The reason why the data type is called a constraint is because the data can be limited to a range or different types, so that the user can only be restricted to enter the corresponding type, otherwise an error will be reported.

         Below are a few typical examples of different types.

1. Numeric type

- integer type

tinyint [[unsigned](n)] [zerofill];

int [[unsigned](n)] [zerofill];

......

        unsigned : Used to distinguish whether this numeric type is signed or unsigned.

        The space allocated by tinyint is 1byte (2^8), so the signed value ranges from -128 to 127, and the unsigned value ranges from 0 to 255.

        The space allocated by int is 4byte (2^32), so the signed value range is -2^31 ~ 2^31 - 1, and the unsigned value is 0~2^32 - 1;

        n represents the number of zeros to be supplemented under the display of n widths (note that only the constraint zerofill will take effect), such as n = 3, which means 001 when it represents 1. It should be noted that the zerofill constraint is added Finally, only unsigned can take effect, so it will be filled with unsigned by default. (The fit of table constraints will be specifically discussed later)

        The following focuses on demonstrating the constraints of zerofill. In the User1 table, we insert two attributes: test1 and test2, and use alter to modify and insert:

alter table User1 add test1 tinyint(3) zerofill after pw;
alter table User1 add test2 int(5) zerofill after test1;

         Simply insert a few data to get the following result:

-bit type

bit[(M)];

        M represents the number of bits, the default is 1. Up to 64 bits.

        It should be noted that the bit corresponds to the bit type. When extracted according to the corresponding encoding rules, it is not extracted directly like the integer type, but is extracted as an ASCII value.

        For example, use the following example to illustrate the difference between the bit type and other numerical types:

        Insert an attribute test3 into the table User1, define the bit(7) (2^7), and then insert 97 with the id at the same time, and see the effect when selecting the query data:

alter table User1 add test3 bit(7) after ID;
insert into User1(ID, test3) values(97, 97);
select * from User1;

        It can be found that although 97 is inserted at the same time, according to the verification rules, the bit type data is obtained according to the ASCII code identification, 97 corresponds to the letter a, and the int is directly taken out according to the numerical value. 

- Decimal type

float[(M, D)] [unsigned];

decimal[(M, D)] [unsigned];

Parameter explanation :

        M: Indicates the display width. M >= number of decimals + number of integers

        D: the number of decimal places

        The difference between float and decimal: decimal precision is higher than float

        Occupies 4bytes.

Note :

        If the number of decimal places of the inserted element exceeds D, there are different rounding strategies. In my current environment, it is rounded (excluding 5).

        For unsigned float(4, 2), the value range is 0 ~ 99.99

        Let's verify the fact of rounding, add the attribute f1 to the table User1, indicating that a floating-point number has a width of 4, and the decimal occupies 2 digits, and insert 9.985 and 9.986.

alter table User1 add f1 float(4, 2);
insert into User1 values(9.985);
insert into User1 values(9.986);

 

         It can be found that although the decimal part exceeds D, the data can be inserted normally for rounding (excluding 5). (Note that each version of mysql has a different strategy, and my current version supports this)

         If the number of digits in the integer part is greater than n - the number of decimal places will directly report an error.

        For float and decimal types, we set (10, 8) to use 23.12345612 to insert respectively, and then we can know the result after selecting the query.

        It can be found that the storage precision of float is indeed lacking, but the precision of decimal is very good. So the essential difference between the two lies in the problem of storage accuracy. If you need high precision, you can choose decimal.

2. Text type

char(size);

varchar(size);

Parameter explanation :

        char is a fixed-length character string, and varchar is a variable-length character string.

        Where size represents the number of characters that can be represented. The maximum number of chars is 255, and the maximum number of varchars is 65535 bytes (the length varies according to the size of the encoded characters, and 3bytes are required to record the byte of each character, so the number of effective characters is 65532bytes).

Note :

        For the char type, because it is a fixed-length string, the space to be opened up is strictly in accordance with the size given by size. If the encoding format is utf8, a character uses 3 bytes, then the size of the space opened up by char at this time is size * 3;

        For the varchar type, it is a variable string, which means that the application length is dynamically applied, and size only limits the maximum length. In mysql, the byte of the character is changed in (1 ~ 3), which is related to the encoding, and utf8 is 3. In addition, if the stored data does not exceed 255 bytes, the actual storage space occupied is the actual length of the data plus one byte for storing length information. If the stored data is longer than 255 bytes, two bytes are required. Bytes store length information. At this time, the size opened by varchar is: (n is the actual number of characters, n<= size)

        if <= 255:n*3 + 1;

        else n*3 + 2;

        Therefore, if the length of a piece of data is determined, using char to fix the string can save more space, and if it is not sure, using varchar can save more space.

        For example, when inserting phone and name, the phone can use a fixed length, and the name is a variable length.

alter table User1 add c1 char(11) commit '电话11固定长度';
alter table User2 add c2 varchar(10) commit '名字不超过10个字符';

 

 

  

3. Date time type

date;

datetime;

timestamp;

Parameter explanation :

        Date representation format: 'yyy-mm-dd', representing year, month and day, occupying 3 bytes.

        Datetime format: 'yyy-mm-dd HH:ii:ss' means year, month, day, hour, minute, second, occupying 8 bytes.

        timestamp is a timestamp, occupying 4 bytes. The datetime format will be displayed when displaying the query, and the user does not need to display the insertion (default is set), and the time stamp at the time of insertion will be automatically obtained, and the date and time will be displayed. and set to non-null. All are formed by default. (Subsequent insertion or modification will be automatically updated)

        

        All three have different application scenarios, and the size of the space occupied is negligible .

        Add attributes d1, d2, and d3 to the User1 table to detect the characteristics of the three attributes.

alter table User1 add d1 date;
alter table User1 add d2 datetime;
alter table User1 add d2 timestamp; 

         First insert data: insert into User1(d1, d2) values('1949-10-01', '2008-10-01 16:41:32');

        It can be found that d3 has automatically updated the timestamp when it was inserted. When we modify it, it will also change (without doing any processing on d3).

        update User1 set ID=3 where ID is NULL;

         It can be found that as long as the current tuple is modified (involving the learning of the DML data manipulation language), d3, that is, the timestamp, will be updated. 

4. enum and set types

enum('option1', 'option2', ...) ;

set('Option 1', 'Option 2', ...) ;

Parameter explanation :

        enum is similar to the enumeration in C, and represents the radio type in mysql. That is to say, if you restrict data insertion to this data attribute, it must be one of the enum options. In fact, the bottom layer of each option is a number, 'option 1' can be replaced by 1, starting from 1, up to 65535 options.

        set is a multi-choice type, and it is limited to only these indefinite items when entering this data attribute. For the sake of efficiency, these bottom layers are also digital storage, but use the bitmap structure. For example, if there are currently 3 options, it means that the first option is 001 = 1, the second 010 = 2, the first and second 011 = 3... and similar to this. The maximum number of options expressed is 64 (2^64)

        For example, I add attributes e and s to our User1 table, where e is enum including a, b, c; s is set including u, f, o.

alter table User1 add e enum('a', 'b', 'c');
alter table User1 add s set('u', 'f', 'o');

         We just insert a few data:

insert into User1(e, s) values('a', 'u');
insert into User1(e, s) values('c', 'f,o');
insert into User1(e, s) values(2, 7);  -- 'b' 'u,f,o'

         Then there is a certain problem with the query of set here. Because an attribute strictly distinguishes different attributes, we want to find only f tuples in the data, and directly select * from User1 where s='f'; is it possible? Of course not, we need a function to help us solve this problem.

find_in_set()

        select find_in_set('a', 'a,b,c');

        For the function find_in_set(a, b), it is possible to extract the corresponding position from the combination of single element a and b, starting from 1, and not being 0. Therefore, corresponding to where in the select query statement, as long as the search returns >1. We can then find elements where only 'f' exists.

select * from User1 where find_in_set('f', s);

Guess you like

Origin blog.csdn.net/weixin_61508423/article/details/130127959