mysql> SELECT CONCAT('ab',' cd ','ef') AS str1,
-> CONCAT('ab',LTRIM(' cd '),'ef') AS str2,
-> CONCAT('ab',' cd ','ef') AS str3,
-> CONCAT('ab',RTRIM(' cd '),'ef') AS str4;
+--------------+--------------+--------------+-------------+
| str1 | str2 | str3 | str4 |
+--------------+--------------+--------------+-------------+
| ab cd ef | abcd ef | ab cd ef | ab cdef |
+--------------+--------------+--------------+-------------+
1 row in set (0.03 sec)
提示:上述语句中,字符串“cd”两侧各有一个空格。在语句CONCAT('ab',LTRIM(' cd '),'ef') AS str2中,函数LTRIM(' cd ')将cd左侧的空格删除了,所以语句执行结果为abcdef;在语句CONCAT('ab',RTRIM(' cd '),'ef') AS str4中,函数RTRIM(' cd ')将cd右侧的空格删除了,所以语句执行结果为abcdef。
函数TRIM(str)用于删除字符串开头和结尾的空格,另外,它还可以删除字符串两侧的指定字符。
实例20:执行SQL语句,验证函数TRIM(str)的应用。执行结果如下
mysql> SELECT CONCAT('ab',' cd ','ef') AS str1,
-> CONCAT('ab',TRIM(' cd '),'ef') AS str2,
-> TRIM('a' from 'aabacaa') AS str3;
+--------------+--------------+--------------+
| str1 | str2 | str3 |
+--------------+--------------+--------------+
| ab cd ef | abcdef | bac |
+--------------+--------------+--------------+
1 row in set (0.00 sec)
可以看到,在语句CONCAT('ab',TRIM(' cd '),'ef') AS str2中,函数TRIM(' cd ')将cd两侧的空格全部删除了,所以合并字符串的结果为abcdef;在语句TRIM('a' from 'aabacaa') AS str3中,函数TRIM('a' from 'aabacaa')将字符串aabacaa两侧的指定字符a全部删除了。