如果字符串小于特定长度,则在MySQL中显示子字符串,如果大于则显示定制消息?
为此,您可以使用substring()
MySQL中的函数。对于条件,请使用MySQLCASE语句。让我们首先创建一个-
mysql> create table DemoTable1402 -> ( -> EmployeeName varchar(40) -> );
使用insert在表中插入一些记录-
mysql> insert into DemoTable1402 values('Adam Smith'); mysql> insert into DemoTable1402 values('Chris Brown'); mysql> insert into DemoTable1402 values('David Miller'); mysql> insert into DemoTable1402 values('Carol Taylor');
使用选择显示表中的所有记录-
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)