如果字符串小于特定长度,则在 MySQL 中显示子字符串,否则显示自定义消息?
为此,你可以在 MySQL 中使用 substring() 函数。对于条件,使用 MySQL CASE 语句。我们首先创建一个 -
mysql> create table DemoTable1402 -> ( -> EmployeeName varchar(40) -> ); Query OK, 0 rows affected (0.62 sec)
使用 insert 在表中插入一些记录 -
mysql> insert into DemoTable1402 values('Adam Smith'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable1402 values('Chris Brown'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable1402 values('David Miller'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable1402 values('Carol Taylor'); Query OK, 1 row affected (0.10 sec)
使用 select 从表中显示所有记录 -
mysql> select * from DemoTable1402;
这将生成以下输出 -
+--------------+ | EmployeeName | +--------------+ | Adam Smith | | Chris Brown | | David Miller | | Carol Taylor | +--------------+ 4 rows in set (0.00 sec)
以下是在 MySQL 中,如果字符串小于特定长度,则显示子字符串,否则显示自定义消息的查询 -
mysql> select *, case when char_length(EmployeeName) <=11 then substring(EmployeeName,1,5) -> else 'EmployeeName is greater than 11' -> end as Result -> from DemoTable1402;
这将生成以下输出 -
+--------------+---------------------------------+ | EmployeeName | Result | +--------------+---------------------------------+ | Adam Smith | Adam | | Chris Brown | Chris | | David Miller | EmployeeName is greater than 11 | | Carol Taylor | EmployeeName is greater than 11 | +--------------+---------------------------------+ 4 rows in set (0.04 sec)
广告