在 MySQL 中获取字段值小于 5 个字符的行?
要获取字段值小于 5 个字符的行,你需要使用 LENGTH() 函数。语法如下 −
SELECT *FROM yourTableName WHERE LENGTH(yourColumnName) < 5;
为了理解上述语法,让我们创建一个表。创建表的查询如下 −
mysql> create table fieldLessThan5Chars -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> yourZipCode varchar(10) -> ); Query OK, 0 rows affected (0.52 sec)
现在你可以使用插入命令在表中插入一些记录。查询如下 −
mysql> insert into fieldLessThan5Chars(yourZipCode) values('35801'); Query OK, 1 row affected (0.10 sec) mysql> insert into fieldLessThan5Chars(yourZipCode) values('3580'); Query OK, 1 row affected (0.20 sec) mysql> insert into fieldLessThan5Chars(yourZipCode) values('90001'); Query OK, 1 row affected (0.40 sec) mysql> insert into fieldLessThan5Chars(yourZipCode) values('100'); Query OK, 1 row affected (0.20 sec) mysql> insert into fieldLessThan5Chars(yourZipCode) values('10'); Query OK, 1 row affected (0.17 sec) mysql> insert into fieldLessThan5Chars(yourZipCode) values('0'); Query OK, 1 row affected (0.15 sec) mysql> insert into fieldLessThan5Chars(yourZipCode) values('90209'); Query OK, 1 row affected (0.11 sec) mysql> insert into fieldLessThan5Chars(yourZipCode) values('33124'); Query OK, 1 row affected (0.20 sec)
使用 select 语句显示表中的所有记录。查询如下 −
mysql> select *from fieldLessThan5Chars;
以下是输出 −
+----+-------------+ | Id | yourZipCode | +----+-------------+ | 1 | 35801 | | 2 | 3580 | | 3 | 90001 | | 4 | 100 | | 5 | 10 | | 6 | 0 | | 7 | 90209 | | 8 | 33124 | +----+-------------+ 8 rows in set (0.00 sec)
示例
下面是获取字段值小于 5 个字符的所有行的查询 −
mysql> select *from fieldLessThan5Chars where length(yourZipCode) < 5;
输出
+----+-------------+ | Id | yourZipCode | +----+-------------+ | 2 | 3580 | | 4 | 100 | | 5 | 10 | | 6 | 0 | +----+-------------+ 4 rows in set (0.00 sec)
广告