SQL notes (3) - MySQL data types

To learn MySQL, you should usually learn the data type first, because whether it is development or MySQL, each data object has its corresponding data type. MySQL provides a wealth of data types. For example, when creating a table, you need to specify the column When inserting data into the table, it is also necessary to pass values ​​strictly according to the type of the corresponding column. So this part is very important!

The previous two articles directly started some operations. According to the normal learning steps, this is not correct, but the previous ones mainly involve some basic operations, so it is still too late to add~

MySQL data type

MySQLSJLX

value type

strict numeric data type

  • TINYINT

    TINYINT is a data type in MySQL and SQL Server that uses only 1 byte of storage and is used to store integer values ​​with a small range. In MySQL, TINYINT can store integers ranging from -128 to 127, but it can be defined as an unsigned type through the UNSIGNED keyword , and 0 to 255 can be used for storage. In SQL Server, TINYINT is stored in the range 0 to 255.

    In development, you can use the TINYINT type to store information such as status identifiers or enumeration values , because using the TINYINT type can effectively reduce the storage space occupied. At the same time, when performing calculations, using the TINYINT type can also improve calculation efficiency, because the TINYINT type occupies less storage space than other integer data types.

  • SMALLINT

    SMALLINT is an integer data type used to store data larger than TINYINT but smaller than INT. It occupies two bytes of storage and ranges from -32,768 to 32,767 (0 to 65,535 if the UNSIGNED keyword is used).

    The SMALLINT data type is typically used in situations where small integer values ​​are required, such as statistics, calculations, and so on. In actual development, it is often used to store data such as status codes and quantities. For example, in an e-commerce website, the SMALLINT type can be used to store the status code of the order, such as 0: pending payment, 1: completed, 2: canceled and so on.

    In MySQL, you can use the following SQL statement to create a table with fields of type SMALLINT:

    CREATE TABLE example_table (
    id INT PRIMARY KEY,
    small_number SMALLINT
    );
    

    In the above code, example_tablethe table contains two fields, id and small_number, where the data type of small_number is SMALLINT.

  • MEDIUMINT

    MEDIUMINT is an integer data type used to store data larger than SMALLINT but smaller than INT. It occupies three bytes of storage and ranges from -8,388,608 to 8,388,607 (0 to 16,777,215 if the UNSIGNED keyword is used).

    The MEDIUMINT data type is typically used when small integer values ​​are required, such as user IDs, visit counts, and so on. In actual development, MEDIUMINT can be used to store some medium-scale data. For example, in a blog system, MEDIUMINT type can be used to store the number of views or comments of articles.

    In MySQL, you can use the following SQL statement to create a table with a column of type MEDIUMINT:

    CREATE TABLE example_table (
      id INT PRIMARY KEY,
      medium_number MEDIUMINT
    );
    

    In the above code, example_tablethe table contains two fields, id and medium_number, where the data type of medium_number is MEDIUMINT.

  • INT/INTEGER

    INT is an integer data type used to store data larger than TINYINT, SMALLINT, and MEDIUMINT but smaller than BIGINT. It occupies four bytes of storage and ranges from -2,147,483,648 to 2,147,483,647 (0 to 4,294,967,295 if the UNSIGNED keyword is used).

    The INT data type is usually the preferred type for storing integer values ​​such as user ID, age, order quantity, amount, etc. In actual development, INT can also be used to store some large-scale data, such as the number of views, the number of likes, etc.

    In MySQL, you can use the following SQL statement to create a table containing INT type fields:

    CREATE TABLE example_table (
      id INT PRIMARY KEY,
      age INT
    );
    

    In the above code, example_tablethe table contains two fields id and age, where the data type of age is INT.

    except I

  • BIGINT

    bigint is an integer data type. It has a larger value range than the int data type, occupies the largest storage space among all integer types, and can be used to store larger integer values.

    Specifically, the bigint data type uses 8 bytes of storage space, and the value range that can be stored is -9223372036854775808 to 9223372036854775807. If the UNSIGNED keyword is used, the range is 0 to 18446744073709551615.

    In practical applications, the bigint data type is usually used in scenarios that need to store very large integer values, such as storing order amounts, business numbers, etc.

    Compared with other integer data types, the bigint data type has the advantage that it can store larger values; but the disadvantage is that it uses more storage space, which may be more burdensome when querying and sorting.

    The following is an example SQL statement to create a table with a field of bigint data type in MySQL:

    CREATE TABLE example_table (
      id INT PRIMARY KEY,
      large_num BIGINT
    );
    

    In the above code, example_tablethe table contains two fields, id and large_num, where the data type of large_num is bigint.

  • DECIMAL

    DECIMAL is a fixed-point number data type. Unlike the floating-point data types FLOAT and DOUBLE, values ​​of type DECIMAL are always stored exactly and support a fixed number of decimal places.

    The format of the DECIMAL data type is DECIMAL(p, s), where p represents the total number of digits and s represents the number of digits in the fractional part. The storage space of DECIMAL type is variable length, depending on the value of p and s. For example, DECIMAL(5,2) can store any value from -999.99 to 999.99 and requires 3 bytes of storage.

    The DECIMAL data type is usually used to store currency-related data, such as prices, tax rates, and other scenarios that require precise calculations. For example, in an e-commerce system, the order amount, product price, etc. can be stored using the DECIMAL type.

    The following is an example SQL statement in MySQL to create a table with a column of DECIMAL data type:

    CREATE TABLE example_table (
      id INT PRIMARY KEY,
      price DECIMAL(8, 2)
    );
    

    In the above code, example_tablethe table contains two fields, id and price, where the data type of price is DECIMAL, with a total of 8 digits, including 2 digits for the decimal part.

  • NUMERIC

    NUMERIC is an exact numeric type, also known as DECIMAL. It is used to represent fixed, precise numerical values ​​whose range and precision can be controlled.

    The NUMERIC data type is declared as NUMERIC(p,s), where p represents the precision of the number (the maximum value is 65), and s represents the number of decimal places (the maximum value is 30). In storage, each NUMERIC value occupies a fixed number of bytes, the size of which is affected by its precision and scale.

    NUMERIC is suitable for scenarios that require high-precision digital calculations, such as scientific calculations and financial calculations. In general, NUMERIC is more suitable for processing financial data than FLOAT and DOUBLE.

    The following is an example SQL statement to create a table with a NUMERIC data type field in MySQL:

    CREATE TABLE example_table (
      id INT PRIMARY KEY,
      price NUMERIC(10, 2)
    );
    

    In the above code, example_tablethe table contains two fields, id and price, where the data type of price is NUMERIC, and there are 10 digits in total, including 2 digits in the decimal part.

Approximate Numeric Data Types

  • FLOAT

    FLOAT is a floating-point numeric type used to represent single-precision floating-point numbers. The number of bytes occupied by FLOAT is 4 bytes, and it can store a larger range of data than DECIMAL, but there is a loss in precision.

    The FLOAT data type is declared as FLOAT(p,s), where p represents the total number of digits and s represents the number of digits after the decimal point. In storage, a FLOAT value will occupy 4 bytes, and its size and precision are not necessarily fixed, and can be adjusted according to the actual value.

    FLOAT is suitable for scenarios that require high-speed computing but not high precision requirements, such as scientific computing, image processing, etc. Compared with DOUBLE, FLOAT occupies less storage space, so it can improve data processing efficiency in the case of limited storage space.

    The following is an example SQL statement to create a table with a field of FLOAT data type in MySQL:

    CREATE TABLE example_table (
      id INT PRIMARY KEY, 
      temperature FLOAT(5,2)
    );
    

    In the above code, example_tablethe table contains two fields, id and temperature, where the data type of temperature is FLOAT, with a total of 5 digits, including 2 digits for the decimal part.

  • REAL

    REAL is a floating-point numeric type used to represent single-precision floating-point numbers. The REAL and FLOAT data types are equivalent in MySQL, and both can be used to store floating-point numbers. The difference is that the number of bytes occupied by REAL is 4, and the number of bytes occupied by FLOAT is also 4. This has a smaller footprint than double-precision floating-point numbers (DOUBLE), which can improve database processing performance in some cases.

    When using REAL, you need to be aware of its precision range and loss of precision. Although REAL can store a larger range than DECIMAL, its precision is at risk of being truncated or rounded due to the IEEE floating-point standard. In order to ensure accuracy, it is recommended to use DECIMAL type instead of REAL type when storing currency data.

    The following is an example SQL statement to create a table with a field of REAL data type in MySQL:

    CREATE TABLE example_table (
      id INT PRIMARY KEY, 
      temperature REAL(5,2)
    );
    

    In the above code, example_tablethe table contains two fields, id and temperature, where the data type of temperature is REAL, and there are 5 digits in total, including 2 digits in the decimal part.

  • DOUBLE

    DOUBLE is a floating-point numeric type used to represent double-precision floating-point numbers, which can store real numbers with a larger range and higher precision. The number of bytes occupied by DOUBLE is 8 bytes, which can store a larger range of data while ensuring relatively high precision.

    The declaration method of the DOUBLE data type is DOUBLE(p,s), where p represents the total number of digits, and s represents the number of digits after the decimal point. In storage, a DOUBLE value occupies 8 bytes, its size and precision are fixed, and it is relatively more accurate and reliable.

    In MySQL, DOUBLE is often used to store currency-related information, such as salary, remuneration, profit, etc., to ensure the accuracy and reliability of the data. DOUBLE can also play a good role in scenarios that require high-precision calculations.

    The following is an example SQL statement to create a table with a field of DOUBLE data type in MySQL:

    CREATE TABLE example_table (
      id INT PRIMARY KEY, 
      salary DOUBLE(10,2)
    );
    

    In the above code, example_tablethe table contains two fields, id and salary, where the data type of salary is DOUBLE, with a total of 10 digits, of which the decimal part has 2 digits.

BIT

  • BIT

    BIT is a binary numeric type used to store bit data. The BIT type can store two values ​​of 0 and 1, and can also indicate whether a certain state is on or off in some cases.

    The BIT data type is declared as BIT(M), where M represents the number of bits to be stored. In MySQL, the BIT type can store up to 64 bits (8 bytes) of binary data . For example, if you want to store a switch state, you can use the BIT(1) data type, so that only 1 bit is needed to meet the requirements.

    In MySQL, the BIT type is often used to represent Boolean data, such as storing whether the user has logged in or has administrator privileges. In addition, the BIT type can also be used to represent the binary form of a text string, such as the binary form of an IPv4 address.

    The following is an example SQL statement to create a table with a field of BIT data type in MySQL:

    CREATE TABLE example_table (
      id INT PRIMARY KEY, 
      switch BIT(1)
    );
    

    In the above code, example_tablethe table contains two fields, id and switch, where the data type of switch is BIT, which only needs to occupy 1 bit.

    The following is an example of using the BIT type to store the switch state:

    id switch
    1 0
    2 1
    3 0
    4 1

string type

fixed-length string type

  • CHAR

    CHAR is a data type in the MySQL database for storing fixed-length character strings. It needs to specify the maximum length of the string, and the maximum length cannot exceed 255 characters.

    The value of CHAR type is always padded with spaces to a fixed length. If the length of the string is less than the specified length when stored, spaces will be automatically added for padding. When fetching data, the spaces at the end of the string will be automatically removed for display.

    The advantage of the CHAR type is that it is intuitive, easy to handle and sort. In some specific scenarios, such as storing zip codes, phone numbers, etc., the CHAR data type with a fixed maximum length is suitable for use.

    Generally speaking, the CHAR type is more suitable for storing fixed-length text information, but when using it, you need to pay attention to the storage and space occupation of fixed-length strings.

  • BINARY

    BINARY is a data type in MySQL database used to store binary data. It is similar to the CHAR type and needs to specify a fixed length, but BINARY stores binary data instead of string data.

    The value of the BINARY type does not need to be filled with spaces like the CHAR type when stored, because it is a binary number, so there is no problem with spaces. When fetching data, when comparing binary data, MySQL will ensure case insensitivity, and treat it as a binary comparison when comparing.

    The application scenario of the BINARY type is mainly the high-speed processing of massive data. For example, if you want to store a large amount of binary file type data such as pictures, audio, or video, you can use the BINARY type for storage. In addition, binary data can also be used to store encrypted sensitive information, etc.

    It should be noted that when using the BINARY type to store data, since it is a fixed-length binary number type, it will automatically fill in zeros when the length of the data is insufficient, and will truncate when the length exceeds, which may cause some data loss, so Use requires careful consideration of how data is stored and read.

variable length string type

  • VARCHAR

    VARCHAR is a data type in the MySQL database for storing variable-length character strings. Compared with the fixed-length CHAR type, VARCHAR is more flexible, because it can dynamically adjust the occupied storage space, saving the use of storage space.

    When creating a table, you need to specify the maximum length of the VARCHAR column. If the actual length of a row is less than the specified maximum length when filling data, only the storage space corresponding to the actual length will be occupied . For example, if a VARCHAR column of length 10 is filled with a string of length 5, only 5 characters of storage will be consumed.

    If a VARCHAR(10) column is entered with a string of length 15, MySQL will only store the first 10 characters in the column, and the following 5 characters will be truncated and will not be stored in the on the list.

    Of course, you can also modify the default interception behavior by setting the SQL mode. For example, if the mode is set STRICT_TRANS_TABLES, when data exceeding the maximum length is entered into a VARCHAR column, MySQL will report an error and refuse to store the data. And if the mode is set TRADITIONAL, MySQL ignores the part exceeding the maximum length and fills the column with valid data close to the maximum length.

    Since VARCHAR stores string type data, it has some special rules when storing and comparing strings. First, the collation of the VARCHAR type is related to the character set, because in different character sets, the ASCII code of the same character may be different. Secondly, you need to pay attention to the case sensitivity of the VARCHAR type to the string, which is related to the language setting of the MySQL database itself.

    In addition, it should be noted that the maximum length of the VARCHAR type cannot exceed 65535 characters. If you need to store longer text information, you need to use the TEXT or LONGTEXT type.

  • VARBINARY

    VARBINARY is a binary data type in MySQL used to store non-text data such as images, audio, video, etc. The maximum length of VARBINARY is 65,535 bytes , which can store binary data of any length.

    Unlike VARCHAR, VARBINARY stores data in raw binary form, not character form, so there are no character encoding issues. When converting other data types to binary or VARBINARY types, the data is padded or truncated on the left. Padding uses hexadecimal zeros. Therefore, if you need to transfer binary data between various systems, using the VARBINARY type may be the easiest way.

    Data of type VARBINARY can be manipulated through INSERT, UPDATE, and SELECT statements, and can also be mixed with other data types. However, you need to be more careful when using VARBINARY data types than with other regular data types because they require more memory and processor time. In addition, query operations on VARBINARY type data also require special processing.

large object type

  • TINYBLOB

    TINYBLOB is a binary data type in the MySQL database, which can store up to 255 bytes of binary data. Compared with other binary data types (such as BLOB, MEDIUMBLOB, and LONGBLOB), TINYBLOB can store a smaller amount of data, but therefore occupies a smaller storage space, and is suitable for storing a small amount of binary data with a small capacity.

    In practical applications, TINYBLOB is often used to store some smaller binary data, such as:

    1. Icons: Website or application icons are usually small and can be stored using the TINYBLOB type.
    2. Thumbnails: For websites or applications that need to display a large number of pictures, it is usually necessary to generate thumbnails to improve user experience. These thumbnails are usually no more than a few hundred bytes in size and can be stored using the TINYBLOB type.
    3. Small sound effect files: There may be some simple sound effects (such as button clicks) in some games or animation applications. These sound effect files are usually small and can be stored in TINYBLOB type.

    In the above scenarios, since the amount of data to be stored is small, using the TINYBLOB type can save storage space and improve database performance. In addition, when storing binary data, care should be taken to perform appropriate encoding and format conversion to ensure the correctness and integrity of the data.

  • BLOB

    BLOB is a binary data type in MySQL database, which can store binary data of any length. Compared with other binary data types (such as TINYBLOB, MEDIUMBLOB, and LONGBLOB), BLOB can store a larger amount of data and is suitable for storing large binary files such as pictures, audio and video.

    In practical applications, BLOB is often used in the following scenarios:

    1. Image storage: Websites or applications need to store a large number of images, which are usually stored in the database in binary format. For example, on an e-commerce website, product images can be stored using the BLOB type.
    2. Audio and video storage: For applications that need to store large audio and video files, such as video cloud platforms, online audio and video websites, etc., you can use the BLOB type to store these files.
    3. Document storage: Some applications need to store large document files, such as PDF files, Word documents, etc. These files can be stored using the BLOB type.

    Since the BLOB type can store binary data of any length, it is necessary to consider storage space occupation and read/write performance when storing large files. Generally speaking, storing large files in the database will have a greater impact on database performance, so in practical applications, technologies such as distributed file systems are usually used to store large files.

    • example

    To store a picture in MySQL as a BLOB, you can implement the following steps:

    1. Connect to a MySQL database using a programming language.
    2. Open the file, read the image's binary data, and store it in a variable.
    3. Construct an INSERT SQL statement, passing the variable as a parameter to the SQL statement. For example, suppose you want to store an image named "example.jpg" in the blob field of a table named "image_table", you can use the following code:
    with open("example.jpg", "rb") as image_file:
        image_data = image_file.read()
    
    # 将图片数据插入数据库
    cursor.execute("INSERT INTO image_table (image_blob) VALUES (%s)", (image_data,))
    

    In this example, the image file is first opened using Python's built-in open() function, and the data in it is read in binary mode ("rb"). Then save the read data in a variable named image_data.

    Next, store the binary data in the variable into the database by executing the SQL INSERT statement. When executing the SQL statement, the execute() method provided by the Python MySQL driver is used, and the image_data is passed as a parameter to the placeholder "%s" in the SQL statement.

  • MEDIUMBLOB

    MEDIUMBLOB is one of the BLOB types in MySQL, used to store binary large objects (Binary Large Object), and can store binary data with a maximum size of 16MB .

    In actual scenarios, the MEDIUMBLOB data type is usually used to store some binary data that needs to be read and updated frequently, such as pictures, audio, etc. Compared with the LONGTEXT type, the MEDIUMBLOB type can better handle extremely large binary data, and has better performance and less storage space requirements. In addition, for some MySQL-based applications, the MEDIUMBLOB type can also be used to cache some data to improve the performance and response speed of the application.

    For example, an online music website might use the MEDIUMBLOB data type to store user-uploaded music files for online playback and thereby improve the user experience. In addition, some e-commerce websites may also use MEDIUMBLOB to store product images for display to users.

  • LUNG BLOB

    LONGBLOB is one of the BLOB types in MySQL, used to store binary large objects (Binary Large Object), and can store binary data with a maximum size of 4GB .

    The LONGBLOB data type is usually used to store very large binary data that needs to be read and updated frequently , such as image files, audio and video files, etc. Compared with several other BLOB types, LONGBLOB can handle the largest binary data and has higher performance, but also consumes more storage space. In some specific scenarios, such as large-scale upload and download of binary data, LONGBLOB may be used to improve processing speed and avoid repeated I/O operations.

    For example, a video site might use the LONGBLOB type to store user-uploaded video files for online playback. In addition, some scientific research institutions may use LONGBLOB to store a large amount of scientific data for daily query and analysis.

  • TINYTEXT

    TINYTEXT is one of the data types used to store short text strings and it is capable of storing text data with a maximum size of 255 characters .

    TINYTEXT is usually used to store short text content, such as titles, descriptions, notes, summaries, etc. Unlike MEDIUMTEXT and LONGTEXT, TINYTEXT requires less storage space, but can only store relatively little text data.

    For example, in a news website, TINYTEXT can be used to store the title and summary information of each article, so that it can be displayed to users on the list page. In addition, in some applications, such as blogs and forums, TINYTEXT is often used to store short text information such as comments and replies.

  • TEXT

    The TEXT type is a data type used to store large amounts of text data. Compared with the VARCHAR type, the TEXT type can store longer character strings, with a maximum length of 65,535 characters . At the same time, it also supports more character set encoding methods, such as UTF-8, GB2312, etc. If you need to store data longer than 65,535 characters, you can use the MEDIUMTEXT or LONGTEXT types.

    Unlike the VARCHAR type, the TEXT type does not need to specify a maximum length, and the length of the stored string can change dynamically. This makes it suitable for storing some data of variable length, such as text data such as articles and comments.

    When using the TEXT type, it should be noted that since it stores a large amount of text data, it will take up a large storage space and query time. Therefore, in actual use, the appropriate data type should be selected according to specific business needs.

  • MEDIUMTEXT

    The MEDIUMTEXT type refers to a data type that can store longer text data, with a maximum length of 16,777,215 characters .

    The maximum storage size of various TEXT types is given in [ 4 ]. The maximum storage size of the MEDIUMTEXT type is 16MB, which is larger than the TEXT type (the maximum storage size is 64KB). Therefore, if you need to store data longer than 64KB but less than 4GB, you can choose the MEDIUMTEXT type.

    It should be noted that since the MEDIUMTEXT type takes up a large storage space and query time, it should be used according to specific business needs to avoid meaningless waste.

  • LONGTEXT

    LONGTEXT is a data type used to store large amounts of text data. It can be used to store string or text data up to 4GB in length.

    It should be noted that since it can store large data, storage space and query efficiency need to be considered when using it. In addition, if you need full-text search and other functions, you can consider using the full-text search engine MySQL FTS that comes with MySQL.

enumerated type

  • ENUM

    The ENUM type in MySQL is a data type used to store enumeration values. Enumeration (Enum) is to put several predefined constants in a collection, and use the elements in this collection to represent a specific state or attribute value .

    [ 1 ] In MySQL, the ENUM type defines one or more enumeration values, and each enumeration value is specified as a string and separated by commas. When inserting data, only one of the defined values ​​of the ENUM type can be inserted. For example:

    CREATE TABLE example (
      id INT NOT NULL AUTO_INCREMENT,
      gender ENUM('male', 'female'),
      PRIMARY KEY (id)
    );
    
    INSERT INTO example (gender) VALUES ('male');
    

    In the above example, we created a exampletable named , which contains an ID field and a genderfield of type ENUM. genderThe field only allows one of the two values ​​male or female to be selected, and no other value can be inserted.

    It should be noted that since the optional values ​​of the ENUM type are pre-defined, careful consideration is required when designing the table structure to ensure that the enumeration values ​​will not change. At the same time, it should be noted that when performing operations such as query and sorting, you can use the integer value of the enumeration value instead of the string value to improve query efficiency.

collection type

  • SET

    The SET type in MySQL is a data type used to store set values. Set (Set) is to put several predefined constants in a set, and use the elements in this set to represent a specific state or attribute value, similar to the enumeration type.

    [ 1 ] In MySQL, the SET type is used to define one or more set values, and each set value is specified as a string and separated by commas. When inserting data, you can choose to use multiple defined values ​​of this SET type and separate them with commas. For example:

    CREATE TABLE example (
      id INT NOT NULL AUTO_INCREMENT,
      colors SET('red', 'green', 'blue'),
      PRIMARY KEY (id)
    );
    
    INSERT INTO example (colors) VALUES ('red, green');
    

    In the above example, we created a exampletable named , which contains an ID field and a colorsfield of type SET. colorsField allows selection of one or more combinations of multiple color values ​​separated by commas.

    It should be noted that since the optional values ​​of the SET type are pre-defined, careful consideration is required when designing the table structure to ensure that the set values ​​will not change. At the same time, it should be noted that when performing operations such as query and sorting, you can use the binary value of the set value instead of the string value to improve query efficiency.

date and time type

  • DATE

    DATE in MySQL is a data type used to represent date values , and its format is 'YYYY-MM-DD'. The date range supported by the DATE type is from '1000-01-01' to '9999-12-31', and uses 4 bytes of storage space.

    There are several ways to interpolate date values. For example, date values ​​can be inserted directly as strings, or you can use MySQL's built-in DATE function for data conversion and formatting.

    The DATE type is often used in applications that need to store and process date-time data, such as scheduling, task scheduling, and so on. Unlike the DATETIME type, the **DATE type does not contain time information, but only represents the date part. ** Therefore, in scenarios where date and time information need to be represented at the same time, it is usually necessary to use the DATETIME type.

  • TIME

    TIME is a data type used to represent time values ​​in the format 'hh:mm:ss'. The time range supported by the TIME type is from '-838:59:59' to '838:59:59', and uses 3 bytes of storage space.

    In MySQL, you can use the TIME type to represent the elapsed time, duration, and duration, etc. , such as the duration of a movie, the playback time of an audio file, and so on.

    At the same time, MySQL provides a series of built-in time functions to operate and calculate the TIME type, for example, the TIMEDIFF function is used to calculate the time difference between two times, the TIME_FORMAT function is used to format the output of time values, and so on.

    It should be noted that although the TIME type can represent a time period exceeding 24 hours, it cannot be directly used to calculate date-related operations . If you need to process date, time, or datetime-related data, you can use other types such as DATETIME or TIMESTAMP.

  • YEAR

    YEAR is a data type used to represent year values, which can store year values ​​in 4-digit format. The YEAR type occupies 1 byte of storage space, and the supported years range from 1901 to 2155.

    In MySQL, the YEAR type is usually used to store data related only to the year. For example, you can use the YEAR type to represent the year a person was born, the year a company was founded, and so on. The YEAR type can also be used to process dates that involve only the year part.

    It should be noted that when the YEAR type is used to store dates, it only contains year information, not month and date information. If you need to store the complete date information of year, month and day at the same time, you should use DATE or DATETIME type.

    When querying a YEAR type field, you can use the YEAR() function to convert it to an integer for easy comparison and calculation. For example:

    SELECT YEAR(date_field) FROM table;
    

    This SQL statement date_fieldconverts a field of type YEAR into an integer for comparison and calculation.

  • DATETIME

    DATETIME is a data type used to represent date and time values ​​in the format 'YYYY-MM-DD hh:mm:ss'. The DATETIME type supports the time range from '1000-01-01 00:00:00' to '9999-12-31 23:59:59', and uses 8 bytes of storage space.

    In MySQL, you can use the DATETIME type to store date and time information, and perform corresponding calculations and comparisons. Different from the DATE and TIME types, the DATETIME type contains both date and time information, and can represent a time point or time period with higher precision . The DATETIME type also supports time zone conversion and handling.

    MySQL provides a series of built-in time functions to operate and calculate the DATETIME type, for example, the TIMESTAMPDIFF function is used to calculate the difference between two times, the FROM_UNIXTIME function is used to convert UNIX timestamps to DATETIME type time values, etc. .

    At the same time, MySQL also supports formatted output of the DATETIME type, which can be customized according to needs, for example:

    SELECT DATE_FORMAT(datetime_field,'%Y-%m-%d %H:%i:%s') FROM table;
    

    This SQL statement datetime_fieldformats the fields of the DATETIME type, and the output format is 'YYYY-MM-DD hh:mm:ss'.

    It should be noted that since the DATETIME type contains both date and time information, it will take up more storage space than the DATE and TIME types when storing and querying. Care should be taken during storage and use to avoid unnecessary waste of space and performance loss.

  • TIMESTAMP

    The TIMESTAMP type is a datetime type used to store date and time data, and its format is 'YYYY-MM-DD HH:MM:SS'. In MySQL, the TIMESTAMP type uses 4 bytes of storage space and can store timestamps from 0:00 on January 1, 1970 to 2038.

    Unlike the DATETIME type, the TIMESTAMP type stores the number of seconds elapsed since January 1, 1970 0:00:00 (UTC time) . When inserting data, if no value of TIMESTAMP type is specified, MySQL will automatically store the current time as the default value. When updating a record, if the record has not been updated, its corresponding TIMESTAMP type field will not change.

    The TIMESTAMP type supports the automatic update function. When defining a table, you can specify the DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP attribute for a TIMESTAMP type field, so that when a new record is inserted or updated, the value of the corresponding field will be automatically updated to the current time.

    It should be noted that because the storage space used by the TIMESTAMP type is small, its precision can only be accurate to the second level, and there is a time zone conversion problem. In MySQL, the UTC time stored in the TIMESTAMP type is related to the current system time zone offset, so time zone issues need to be considered when using the TIMESTAMP type.

JSON type

  • JSON

    JSON (JavaScript Object Notation) is a lightweight, easy-to-read and write data-interchange format. **It is based on the JavaScript programming language, but in MySQL, the data stored in the JSON type is not parsed into JavaScript objects, but stored in plain text. **When the JSON data needs to be used in the application, the program needs to parse it by itself.

    The JSON type in MySQL is a new data type for storing and manipulating data in JSON format. JSON (JavaScript Object Notation) is a lightweight, easy-to-read and write data-interchange format.

    Using the JSON type, you can easily store and query JSON format data in the MySQL database without cumbersome data conversion. For tables containing a large amount of data in JSON format, the JSON type can be used to conveniently process and query the data.

    In MySQL, you can use regular SQL statements to operate JSON-type data , such as SELECT, INSERT, and so on. At the same time, it also provides a series of JSON functions for manipulating and querying JSON type fields. These functions include JSON_OBJECT, JSON_ARRAY, JSON_EXTRACT, etc., which can read or extract data from JSON data, and can add, delete, modify and query JSON type fields.

    The JSON type has the following usages in MySQL:

    • Create a JSON type field

    To create a field with JSON type you can use the following statement:

    CREATE TABLE mytable (
     id INT PRIMARY KEY,
     data JSON
    );
    
    • Insert JSON type data

    When inserting JSON data, you need to use functions such as JSON_OBJECTor to convert the JSON data into a format that MySQL can recognize. JSON_ARRAYFor example:

    INSERT INTO mytable VALUES (1,JSON_OBJECT('name','Alice','age',25,'hobbies',JSON_ARRAY('reading','swimming')));
    

    JSON data can be retrieved using the following statement:

    SELECT data->>'$.name' AS name,data->>'$.age' AS age FROM mytable WHERE data->>'$.name' = 'Alice';
    
    • Query JSON type data

      For tables containing data in JSON format, you can use the built-in JSON functions to query, for example:

    • JSON_EXTRACT: Used to extract data from JSON objects or arrays.

    • JSON_CONTAINS: Used to determine whether a specified string, number or Boolean value is contained.

    • JSON_SEARCH: Search for the specified string in the JSON object or array and return its path.

    For example, use the following statement to query all records of age > 18 in JSON type, where $.agerepresents the field in JSON age:

    SELECT * FROM mytable WHERE JSON_EXTRACT(data, '$.age') > 18;
    
    • Update JSON type data

    You can use the UPDATE statement to update JSON type data. In order to update a specified property in a JSON object, the JSON_SET function can be used. For example:

    UPDATE mytable SET data=JSON_SET(data,'$.age',30) WHERE id=1;
    
    • Delete JSON type data

    To delete a specified node from JSON type data, you can use the JSON_REMOVE function. For example:

    UPDATE mytable SET data=JSON_REMOVE(data,'$.age') WHERE id=1;
    

    The above is how to use the JSON type in MySQL. It should be noted that although the JSON type in MySQL provides a convenient way to store and manipulate JSON format data, it also has some limitations. On the one hand, the JSON type in MySQL does not support indexes, so there may be performance issues when dealing with large data sets. On the other hand, JSON-type data is still stored as text in the MySQL database, so it may be slightly slower when querying large data sets.

spatial data type

The spatial data type in MySQL refers to a data type used to process and store spatial data, such as points, faces, polygons, etc.

Using the spatial data type can facilitate spatial analysis and query, such as calculating the distance between two geometric objects, judging whether a point is in an area, and so on. For example, to search for nearby restaurants on map software, you must use the spatial data type.

The application scenarios are very extensive, such as geographic information system (GIS), telecommunication network planning, logistics route optimization, urban traffic management, etc. For example, if a railway company needs to inquire about the length of a certain railway line and surrounding city information, it can be realized with the spatial data type in MySQL.

MySQL's spatial data type supports a variety of geometric objects, including points, lines, surfaces, etc. These objects can describe various shapes and spatial relationships. When storing, the coordinates of these objects can adopt different spatial reference systems, such as plane coordinate system and geographic coordinate system.

The geographic coordinate system is usually used to describe the spatial position on the surface of the earth, represented by latitude and longitude. The plane coordinate system is used to describe the spatial position on a two-dimensional plane, usually represented by a Cartesian coordinate system. Therefore, when using MySQL's spatial data type for data storage, it is necessary to select an appropriate spatial reference system and its required coordinate system according to the specific situation.

basic geometry type

  • POINT

    In MySQL, the Point type is a spatial data type used to represent a point in a plane or space. It consists of two coordinates, usually described using Longitude and Latitude values.

    There are two common representations of the Point type, which are WKT and WKB formats. Among them, WKT is the abbreviation of Well-Known Text, which is a representation of text format, for example:

    POINT(30.2 50.5)
    

    This Point represents a point with a longitude of 30.2 and a latitude of 50.5.

    WKB is the abbreviation of Well-Known Binary, which is a binary format representation, usually used to store and transmit spatial data, for example:

    0x00000000010C9DDB51B81E85EB51B81E85EB
    

    The binary representation of this Point is composed of double-precision X coordinates and Y coordinates, and an SRID value (Spatial Reference Identifier).

    When using the Point type for data storage, you need to pay attention to selecting an appropriate coordinate system and spatial reference system, and understand how to handle spatial queries and operations. In addition, MySQL also provides many functions and operators related to the Point type. For example, the ST_Distance() function is used to calculate the distance between two Points, and the ST_Contains() function is used to determine whether a Point is contained in another geometric object, etc. wait.

  • LINE STRING

    LINESTRINGm is used to describe a line segment composed of an ordered set of points. Different from the POINT type, LINESTRING contains multiple points, and each line segment is composed of a connecting line between two adjacent points.

    The representation mode of LINESTRING type is similar to that of POINT type, and it can also be represented in WKT or WKB format. For example, the following is a LINESTRING in WKT format:

    LINESTRING(0 0, 10 10, 20 25, 50 60)
    

    This LINESTRING consists of 4 points, namely (0, 0), (10, 10), (20, 25) and (50, 60), which are connected in turn to form a line segment.

    When using MySQL's spatial data type for data storage, you need to select an appropriate coordinate system and spatial reference system, and understand how to perform spatial queries and operations. MySQL provides many functions and operators related to the LINESTRING type, for example, the ST_Intersects() function is used to determine whether two line segments intersect, the ST_Length() function is used to calculate the length of a line segment, and so on.

    In addition, it should be noted that the LINESTRING type in MySQL is similar to the LineString type in the GeoJSON standard, and can also be represented by a coordinates array. The array contains the latitude and longitude or coordinate information of multiple points, and a line segment can be formed by connecting these points.

  • POLYGON

    POLYGON is mainly used to describe closed polygons on a plane. This type is surrounded by a series of ordered points, and each point has two coordinate parameters: X and Y.

    MySQL includes more than 2,000 OEMs, ISVs, and VARs who use MySQL in embedded databases for applications, hardware, and devices, making applications more competitive, getting to market faster, and reducing their cost of sale. At this time, MySQL's polygon type will be widely used.

    Polygon is a data type used in MySQL for graphic planning, map making and other GIS processes, which can store all geometric types. Of course, this includes simple geometric shapes (such as Point, Line, etc.) as well as compound data types (such as MULTIPOINT, MULTILINESTRING, and MULTIPOLYGON).

    In MySQL, the representation of POLYGON can use WKT or WKB format. For example, here is a POLYGON in WKT format:

    POLYGON((0 0, 0 10, 10 10, 10 0, 0 0))
    

    Each polygon is composed of many line loops, so special attention needs to be paid to the structure and topological relationship of the polygon when storing.

    MySQL provides a variety of functions and operators for the POLYGON type. For example, the ST_Contains() function is used to determine whether a point or line is contained in a polygon, and the ST_Area() function is used to calculate the area of ​​a polygon.

Composite geometry type

  • MULTIPOINT

    A type in MySQL MULTIPOINTis a spatial data type used to represent a collection of points. The points can have different coordinates, but are all on the same plane. MULTIPOINTTypes of data can be stored in a MySQL database and can be processed using GIS functions, such as calculating MULTIPOINTthe distance between two types of data or judging whether a point is in a MULTIPOINTtype of data. By using MULTIPOINTthe type, we can store the coordinate information of multiple points in one field for easy management and processing.

  • MULTILINESTRING

    MULTILINESTRINGUsed to represent a collection of line segments. These line segments can have different start and end points, but are all on the same plane. MULTILINESTRINGTypes of data can be stored in a MySQL database and can be processed using GIS functions, such as calculating MULTILINESTRINGthe distance between two types of data or judging whether a point is on a MULTILINESTRINGline segment described by one type of data. By using MULTILINESTRINGthe type, we can store the coordinate information of multiple line segments in one field for easy management and processing.

    Like MULTIPOINTtypes, types are composed MULTILINESTRINGof objects of multiple types. LINESTRINGEach LINESTRINGobject represents a line segment, and MULTILINESTRINGall line segments in a type are combined into a complex geometric object. Note that MULTILINESTRINGeach segment in a type must be connected to an adjacent segment at an endpoint.

  • MULTIPOLYGON

    MULTIPOLYGONUsed to represent complex geometric objects composed of multiple polygons. Each polygon can have different vertices and boundaries, but all lie on the same plane. MULTIPOLYGONTypes of data can be stored in a MySQL database and can be processed using GIS functions, such as calculating MULTIPOLYGONthe distance between two types of data or judging whether a point is MULTIPOLYGONinside a polygon described by one type of data. By using MULTIPOLYGONthe type, we can store the coordinate information of multiple polygons in one field for easy management and processing.

    Like MULTIPOINTtypes and MULTILINESTRINGtypes, types are also composed MULTIPOLYGONof objects of multiple types. POLYGONEach POLYGONobject represents a polygon, and MULTIPOLYGONall polygons in a type are combined into a complex geometry object. It should be noted that MULTIPOLYGONeach polygon in the type must be closed, that is, the first point and the last point of the polygon must be equal.

  • GEOMETRYCOLLECTION

    GEOMETRYCOLLECTIONIt is used to represent a collection of complex geometric objects composed of multiple geometric objects. These geometric objects can be various geometric figures such as points, lines, and polygons. GEOMETRYCOLLECTIONTypes of data can be stored in a MySQL database and can be processed using GIS functions, such as calculating GEOMETRYCOLLECTIONthe distance between two types of data or judging whether a certain point is in GEOMETRYCOLLECTIONa collection of geometric objects described by a type of data. By using GEOMETRYCOLLECTIONthe type, we can store the coordinate information of multiple geometric objects in one field for easy management and processing.

    It should be noted that GEOMETRYCOLLECTIONeach geometry object in the type must have its own type and geometry. Therefore, when dealing with GEOMETRYCOLLECTIONtypes of data, we need to first determine the type of each geometric object and its corresponding geometric structure.

unconstrained geometry type

  • GEOMETRY

    GEOMETRY is used to store and process coordinate information of geometric objects. These geometric objects can be various geometric figures such as points, lines, surfaces, and polygons. MySQL supports multiple subtypes of GEOMETRY types, such as POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON, and GEOMETRYCOLLECTION.

    In MySQL, we can use the GEOMETRY type to represent the coordinate information of a certain geometric object, and can process it by using GIS functions, such as calculating the distance between two GEOMETRY type data or judging whether a point is in a GEOMETRY type of data described in the geometry object. For all GEOMETRY types, MySQL provides a series of GIS functions so that we can process and manage these data.

    It should be noted that for each GEOMETRY type, it is stored and processed slightly differently. For example, for GEOMETRY data of POINT type, we only need to store its coordinate values; for GEOMETRY data of POLYGON type, we need to store the coordinate values ​​of multiple line segments and the coordinate values ​​of multiple holes that may be contained inside.

other types

  • BOOLEAN

    The Boolean type has only two possible values: TRUE and FALSE. In MySQL, the Boolean type is usually stored using the TINYINT(1) data type. When using TINYINT(1) to represent the Boolean type, 0 represents FALSE and 1 represents TRUE. MySQL's Boolean type can be used in conditional statements, comparison operations, and logical operations.

    It should be noted that the conversion rules between the Boolean type and other data types in MySQL are slightly different. In MySQL, when converting a Boolean type to an integer, TRUE will be converted to 1, and FALSE will be converted to 0. Conversely, when converting an integer to a Boolean, 0 is converted to FALSE, and all other non-zero values ​​are converted to TRUE.

  • SERIAL

    MySQL's SERIAL type is an integer type used to store a self-increasing sequence of numbers. It is usually used as the primary key of the table to ensure that each record has a unique identifier in the table. Whenever a new record is inserted into the table, MySQL will automatically increment the value of the SERIAL type field by 1 to generate a new unique identifier to distinguish it from other records.

    It should be noted that the field of the SERIAL type may appear "empty", even if no data has been deleted. For example, if you insert 3 records into the table and then delete the 2nd record, the next time you insert a new record, MySQL will automatically set the ID of the record to 4 instead of reusing the ID of 2. Therefore, for arrays that require continuous self-increment, you should avoid using the SERIAL type and use other integer types, such as INT or BIGINT.

Q&A

bytes and bits

Byte (Byte) and bit (Bit) are the most basic units of computer storage and transmission of data.

  • A byte is equal to 8 bits and is used to represent common characters (such as letters, numbers, punctuation marks, etc.).
  • A bit is the most basic unit used by computer information technology to measure the amount of data, and it is a form of expression of binary numbers 0 and 1.

In computer systems, byte is a commonly used unit of data volume, while bit is often used to measure the transmission rate of computer networks.

The difference between VARBINARY and BLOB in MySQL

In MySQL, both VARBINARY and BLOB are used to store binary data. But there are still some differences between them.

  • VARBINARY stores variable-length binary data, while BLOB stores large binary data.
  • The VARBINARY data type supports up to 65,535 bytes, while the BLOB data type supports up to approximately 4GB of data.
  • For the VARBINARY data type, MySQL is optimized to better handle small binary data, while for large binary data, the BLOB data type is recommended.

Therefore, if you need to store large binary data, you should use the BLOB data type; if you need to store small binary data, you can use the VARBINARY data type.

How to understand variable length and fixed length

In MySQL, "variable length" means that the length of data stored in the database changes according to the actual length of the data ; while "fixed length" means that the data has a fixed length when stored in the database. rigidity.

Specifically, in MySQL, both VARBINARY and VARCHAR are variable-length data types, and the length of stored data is variable, so there is no need to reserve space when storing data (except for some additional storage overhead), thus saving storage space. When storing fixed-length data, data types such as BINARY and CHAR can be used. The data length of these types is fixed, and the occupied space is always fixed regardless of the actual length of the stored data. In addition, in general, variable-length data types are more suitable for storing text data, while fixed-length data types are more suitable for storing binary data, such as audio, video, images, etc.

The difference between CHAR and TEXT

In MySQL, both VARCHAR and TEXT are used to store string-type data, and their main differences lie in storage methods and usage scenarios.

  • VARCHAR: VARCHAR is a variable-length string type, and the maximum length needs to be specified in advance. If the actual stored string length is less than the maximum length, only the actual required storage space will be occupied. VARCHAR is suitable for storing strings with uncertain length but within a certain range, such as names and addresses.
  • TEXT: The TEXT type is a very flexible data type for storing longer texts. It can store character strings whose length exceeds the limit, and can store text data with a maximum size of 65535 bytes. The TEXT type is suitable for storing text data that exceeds the maximum length allowed by VARCHAR, such as articles and comments.

Because VARCHAR is of variable length and does not waste storage space, it is recommended to use VARCHAR type when data of string type needs to be stored. However, for longer text data, in order to avoid data truncation or overflow, the TEXT type should be used.

In MySQL, VARCHAR and TEXT types have the same encoding requirements for strings .

MySQL supports multiple character set encodings, including ASCII, UTF-8, GB2312, etc. In MySQL, both VARCHAR and TEXT types can be encoded using these character sets. Therefore, no matter it is VARCHAR or TEXT type, any character including Chinese can be stored.

However, it should be noted that when using VARCHAR or TEXT to store Unicode characters, UTF-8 encoding should be used. UTF-8 is a variable-length character encoding method, which can represent all characters in the Unicode character set, and saves storage space more than other encoding methods. Therefore, in MySQL, we usually use UTF-8 encoding for data storage and transmission.

The difference between ENUM and SET

Both ENUM and SET in MySQL are used to represent data types with a series of predefined values, but they have the following differences in usage and function:

  1. The number of values ​​ENUM can only select one value from the predefined value list, while SET can select multiple values ​​from the predefined value list.
  2. Storage method ENUM stores the enumeration value as an integer, and SET stores the set value as a binary mask. Therefore, the SET type is more economical in storage space.
  3. Value type The value of ENUM type can be treated as a string or number type, and the value of SET type can only be treated as a string type.
  4. Extensibility Adding new enumeration values ​​to an ENUM column is relatively simple, just adding a new predefined value. Adding a new set value to a SET column is much more complicated, requiring redefinition of all predefined values.

Common time functions of MYSQL

MySQL provides a wealth of time functions, the following are some commonly used time functions and their usage:

  • ADDDATE(): Add a certain number of days to the date.
SELECT ADDDATE('2022-06-30', INTERVAL 10 DAY);
-- 返回值为 '2022-07-10'
  • ADDTIME(): Add a certain time interval to the time.
SELECT ADDTIME('12:30:45', '02:15:20');
-- 返回值为 '14:46:05'
  • DATE(): Extracts the date part from a time.
SELECT DATE('2022-06-30 12:30:45');
-- 返回值为 '2022-06-30'
  • TIME(): Extracts the time part from a time.
SELECT TIME('2022-06-30 12:30:45');
-- 返回值为 '12:30:45'
  • NOW(): Returns the current date and time.
SELECT NOW();
-- 返回值为 '2023-05-01 14:17:09'
  • TIMESTAMPDIFF(): Calculates the difference between two dates/times.
SELECT TIMESTAMPDIFF(MINUTE,'2022-06-30 12:30:45','2022-07-01 13:35:50');
-- 返回值为 1425
  • DATE_FORMAT(): Format the date/time into the specified format.
SELECT DATE_FORMAT('2022-06-30 12:30:45', '%Y-%m-%d');
-- 返回值为 '2022-06-30'
  • STR_TO_DATE(): Converts a string to a date/time.
SELECT STR_TO_DATE('2022-06-30', '%Y-%m-%d');
-- 返回值为 '2022-06-30'
  • DATE_ADD(): Add a certain time interval to the date.
SELECT DATE_ADD('2022-06-30', INTERVAL 1 MONTH);
-- 返回值为 '2022-07-30'

The difference between SERIAL and INT

First, SERIAL is a special type of integer used to store a self-increasing sequence of numbers. Whenever a new record is inserted into the table, MySQL will automatically increment the value of the SERIAL type field by 1 to generate a new unique identifier to distinguish it from other records. The int type does not have this auto-increment function.

Second, fields of type SERIAL have automatically assigned default values. When creating a table, we can set the SERIAL type field as the primary key, and use the AUTO_INCREMENT keyword to specify its initial value and self-increment. In this way, when we insert a new record, MySQL will automatically assign the next available value to this field. The int type requires us to manually assign values.

Finally, because the field of type SERIAL is a special type, the size of its storage space is limited. In MySQL, the SERIAL type usually occupies 4 bytes and can store integers ranging from 1 to 4294967295, while the size of the int type can be flexibly adjusted according to the range we need, from 1 byte to 8 bytes wait.

To sum up, compared with the int type, MySQL's SERIAL type has the special function of self-increment and automatic allocation of default values, but the storage space is limited. We should choose the appropriate data type to store data according to the actual situation.


Original address: https://blog.jiumoz.com/archives/sql-bi-ji-3mysql-shu-ju-lei-xing

Welcome to follow the blogger's personal mini program!

Guess you like

Origin blog.csdn.net/qq_45730223/article/details/130459964