Getting Started with MySQL Practical Basics (13): Data Types

Getting started with the basics of MySQL combat

  1. Getting Started with Basic Knowledge of MySQL Practical Combat (1): Logging In to the Database Command Line
  2. Getting Started with Basic Knowledge of MySQL Practical Combat (2): Statistical sql statement with 24 hours a day data filled with 0 by default
  3. Getting started with the basic knowledge of MySQL combat (3): The solution to the total sales in the past 7 days, the PHP back-end mysql statement, if it is empty on the current day, it will automatically fill in 0
  4. Getting Started with MySQL Practical Basics (4): MySQL Advanced Function CASE WHEN END
  5. Getting Started with Basic Knowledge of MySQL Practical Combat (5): Output Method of SMARTY Secondary Loop Array
  6. Getting started with the basics of MySQL combat (6): Mysql uses mysqldump to export data error solutions
  7. Getting started with the basic knowledge of MySQL combat (7): the operation scheme of mysql using the source command to import data
  8. Getting Started with Basic Knowledge of MySQL Practical Combat (8): Interpretation of MySQL database instance data table, field naming method and data type setting
  9. Getting Started with Basic Knowledge of MySQL Combat (9): MYSQL Solution for Efficient Query Code Across 4 Tables
  10. Getting Started with Basic Knowledge of MySQL Combat (10): Today, Yesterday, Nearly 7 Days, Nearly 30 Days Solutions Implemented in a Filter Statement
  11. Getting started with the basics of MySQL combat (11): Simple and efficient screening of daily data statistics for the last 7 days to solve echarts daily trading volume column chart
  12. Getting started with basic knowledge of MySQL combat (12): sql statement solution for 24-hour data statistics of the day and yesterday

It is a rare opportunity to "review the past and learn the new" from the topic of "accumulating dust for so long, this thing was collected by you at that time".

1. Mysql field type description

In MySQL, there are various data types that can be used to define fields in a table. Here are some common MySQL field types and their descriptions:

  1. Numeric type:

    • INT: Stores integer values ​​ranging from -2147483648 to 2147483647.
    • BIGINT: Stores large integer values ​​ranging from -9223372036854775808 to 9223372036854775807.
    • FLOAT: Stores single-precision floating-point numbers.
    • DOUBLE: Stores double-precision floating-point numbers.
    • DECIMAL: Store precise decimal values, and you can specify the precision and scale (for example, DECIMAL(10, 2) means that the precision is 10, and 2 digits are reserved after the decimal point).
  2. String type:

    • CHAR: Stores a fixed-length character string, up to 255 characters.
    • VARCHAR: Store variable-length strings with a maximum length of 65535 characters.
    • TEXT: Store variable-length text data, the maximum length is 65535 characters.
    • ENUM: Stores values ​​of enumerated type, allowing to select a value from a predefined list of values.
    • SET: Stores values ​​of set type, allowing selection of one or more values ​​from a predefined list of values.
  3. Date and time type:

    • DATE: Stores a date value (year, month, day).
    • TIME: Stores time values ​​(hours, minutes, seconds).
    • DATETIME: Stores date and time values.
    • TIMESTAMP: Stores timestamps for recording data insertion and update times.
  4. Boolean type:

    • BOOLEAN: Stores a Boolean value, which can represent true or false.
  5. Binary type:

    • BLOB: Store binary large objects, which can store a large amount of binary data.
    • VARBINARY: Store variable-length binary data.

These are commonly used field types in MySQL, each with different characteristics and acceptable value ranges. When creating a table, it is very important to choose the most appropriate field type according to the nature and needs of the data.

2. What is the maximum value of mysql auto-increment Id

The maximum value of MySQL auto-increment ID depends on the data type used. In MySQL, the commonly used auto-increment ID data types are INT, BIGINT, etc. If the INT type is used, the maximum value is 2147483647. If the BIGINT type is used, the maximum value is 9223372036854775807. After the auto-increment ID reaches the maximum value, when data is inserted again, an error will be reported and the auto-increment will stop, and the initial value of the auto-increment ID needs to be reset.

3. The difference between int(10) and int(11)

In MySQL, the difference between INT(10) and INT(11) lies primarily in the display width, not in the data type itself. In fact, INT(10) and INT(11) are identical in terms of storage and range, both being 4-byte integer types.

The numbers in INT(10) and INT(11) simply specify the minimum number of digits required to display an integer with zero padding. For example, INT(10) indicates that the display should be at least 10 bits wide.

However, this does not affect the validity of the stored range or value. Whether you specify a display width of 10 or 11, the INT type can still store integer values ​​in the range -2147483648 to 2147483647. Specifying a display width is primarily used to control the aesthetics and consistency of the output.

The difference between the two can be seen with the following example:

CREATE TABLE 表名 (
    字段名1 INT(10),
    字段名2 INT(11)
);

In the above example, both fields fieldname1 and fieldname2 are of type INT, but fieldname1 will be displayed with a minimum width of 10 digits, and fieldname2 will be displayed with a minimum width of 11 digits. Both field-name1 and field-name2 can store integer values ​​in the same range. The difference is that field name 2 will be wider when the number is displayed with insufficient padding.

All in all, there is no difference between INT(10) and INT(11) in terms of storage and range, only a slight difference in width when displayed. Choosing to use a specific display width depends largely on how consistent and aesthetically pleasing you want your output to be.

insert image description here

Fourth, the difference between varchar(64) and varchar(255)

In MySQL, the difference between VARCHAR(64) and VARCHAR(255) mainly lies in the limitation of storage space and storage capacity.

  1. Storage space: The VARCHAR(64) type can store a variable-length string of up to 64 characters, and the VARCHAR(255) type can store a variable-length string of up to 255 characters. In other words, VARCHAR(255) can hold longer strings.

  2. Storage capacity: Although VARCHAR(64) can store smaller strings, if you need to store longer text or content, VARCHAR(255) provides larger storage space. This makes VARCHAR(255) more suitable for storing longer text fields, such as article content or long descriptions.

It should be noted that the VARCHAR type is a variable-length string type, and it only uses the actual number of characters stored plus some additional byte overhead to save the string data. Therefore, whether it is VARCHAR(64) or VARCHAR(255), only the space required for the actual storage length will be used, and no fixed storage space will be occupied.

When choosing VARCHAR(64) or VARCHAR(255), consider the following factors:

  1. Data length: Select the appropriate VARCHAR length according to the specific data length to be stored. If you are sure that the maximum length will not exceed 64 characters, you can choose VARCHAR(64) to reduce the waste of storage space.

  2. Data type consistency: If the VARCHAR length of other columns in the table is 255, and you want to maintain consistency, you can choose VARCHAR(255).

  3. Performance and Optimization: VARCHARs with shorter lengths generally use less storage space and have better performance. If your data length is limited and stable, you can consider using a shorter VARCHAR length.

To sum up, the main difference between VARCHAR(64) and VARCHAR(255) lies in the limitation of storage space and storage capacity. Choose an appropriate VARCHAR length based on data length, consistency requirements, and performance considerations.

5. The comparison between using integer storage time and DATE storage time

In MySQL, you usually use integer types (such as INT or BIGINT) or date/time types (such as DATE, DATETIME, or TIMESTAMP) to store time data. Here's a comparison of using an integer type and a date/time type to store time:

  1. Storing time with integer types:
    A common way to store time with integer types is by using timestamps. A timestamp is an integer value representing the number of seconds since a specific point in time (usually January 1, 1970 00:00:00 UTC). Advantages include:

    • High storage efficiency: Integer types occupy less storage space.
    • Calculation is convenient: mathematical operations and comparisons can be performed.
    • Sortable: Time sorting can be achieved by sorting integer values.

    But some considerations related to storage time of integer types include:

    • Poor readability: Values ​​are stored and cannot be directly identified as specific dates and times.
    • Manual processing required: Conversion and formatting operations in the application are required to convert integer values ​​to human-readable dates and times.
  2. Date/time type storage time:
    MySQL provides a variety of date/time types, such as DATE, DATETIME, and TIMESTAMP, for storing date and time information. These types have the following advantages:

    • Readable: Stored values ​​are represented in a human-readable date and time format.
    • Automatic functions: Supports automatic updates (such as CURRENT_TIMESTAMP) and built-in functions (such as DATE_FORMAT).
    • More semantic: You can directly operate on dates and times, such as calculations and comparisons.

    Some things to be aware of when using date/time types to store times include:

    • Large storage space: The date/time type takes up a large storage space, especially the DATETIME and TIMESTAMP types.
    • Impact on performance: For tables that are updated frequently, using the TIMESTAMP type may bring additional overhead.
    • Time zone issues: Time values ​​stored by date/time types are affected by the database session's time zone setting.

    To sum up, if you need to perform complex calculations, sorting, and retrieval of time, or require direct storage and display in an easy-to-read date and time format, the date/time type is a more suitable choice. If the goal is storage efficiency and custom calculations, or if you need to interact with other systems (such as external APIs), integer types may be more suitable. Which storage method to use depends on the needs of the application and how the time data is processed.
    insert image description here

6. How to limit the same length as the data table field at the front end

To limit the length of user input on the frontend as with datatable fields, you can use the following methods:

  1. Using HTML's maxlength attribute: For tags or tags, you can use the maxlength attribute to limit the number of characters that the user can enter. For example, if your data table field length is 64, you can set maxlength to 64, as follows:

    <input type="text" maxlength="64" />
    
  2. JavaScript Limit Input Length: You can use JavaScript to limit the length of user input and prevent form submission if the limit is exceeded. The number of characters entered can be calculated in real time by listening to input events (such as input or keydown), and processed according to the field length. Here is an example:

    <input type="text" id="myInput" />
    <span id="charCount"></span>
    <script>
      const input = document.getElementById('myInput');
      const charCount = document.getElementById('charCount');
      const maxLength = 64; // 设置字段长度
    
      input.addEventListener('input', function() {
            
            
        const enteredText = input.value;
        charCount.textContent = `${ 
              enteredText.length}/${ 
              maxLength}`;
        if (enteredText.length > maxLength) {
            
            
          input.value = enteredText.slice(0, maxLength); // 截断超出的部分
        }
      });
    </script>
    

These methods can achieve the same restrictions on the length of data table fields on the front end. Note that length validation is done on the front end to provide better user experience and real-time feedback, but it should also be done on the back end to ensure data integrity and security. Front-end verification is only used as an auxiliary means, and back-end verification is the ultimate guarantee.


@ Leak sometimes

Guess you like

Origin blog.csdn.net/weixin_41290949/article/details/131850507