admin

如何从字段mysql的前20个字符之后选择字符

sql

 select address (first 20 character) as Address1 , 
        address (characters after first 20 if less then 20 then NULL) as Address2
 from customer

如何选择20个字符后的字符串?


阅读 148

收藏
2021-06-07

共1个答案

admin

要获取前20个字符之后的字符(请注意,如果不存在20个字符,该函数将返回一个空字符串):

SELECT SUBSTRING('Some Random Address That is Longer than 20 characters' FROM 20);

现在,如果您需要地址2为NULL,则首先检查字符长度:

SELECT if(char_length(address) > 20, SUBSTRING(address FROM 20), NULL);

要获得前20个字符,您可以使用substring函数,如下所示:

SELECT SUBSTRING('Some Random Address', 1, 20);

现在,最终查询可能如下所示:

SELECT SUBSTRING(address, 1, 20) as Address1, 
    IF(CHAR_LENGTH(address) > 20, SUBSTRING(address FROM 20), NULL) as Address2
FROM customer
2021-06-07