Judging field data length in mysql

In the MySQL database, sometimes we need to judge whether the data length in a certain field meets our setting range. At this time, we need to use some functions provided by MySQL to judge.

MySQL provides two functions to get the length of a string:

1. LENGTH(str):返回字符串str的长度,以字节为单位。
2. CHAR_LENGTH(str):返回字符串str的长度,以字符为单位。

When we need to judge whether the data length of a field is less than or equal to or greater than a certain value, we can use the following statement:

SELECT * FROM table_name WHERE LENGTH(field_name)<= length_value;
SELECT * FROM table_name WHERE CHAR_LENGTH(field_name)<= length_value;
SELECT * FROM table_name WHERE LENGTH(field_name) >= length_value;
SELECT * FROM table_name WHERE CHAR_LENGTH(field_name) >= length_value;

Among them, table_name is the name of the table to be queried, field_name is the name of the field whose data length needs to be judged, and length_value is the maximum length set.

The above are the methods and statements for judging the length of field data in MySQL. It should be noted that the LENGTH function calculates the string length in bytes, while the CHAR_LENGTH function calculates the string length in characters.

select length('张三三');
-- 输出结果 9

select char_length('张三三');
-- 输出结果 3

select length('admin');
-- 输出结果 5

select char_length('admin');
-- 输出结果 5

Guess you like

Origin blog.csdn.net/zlfjavahome/article/details/132187610