2012年3月26日 星期一

MySQL 字串合併、字串連接 語法 concat substring

轉自http://arrack.pixnet.net/blog/post/24091939-mysql-%E5%AD%97%E4%B8%B2%E5%90%88%E4%BD%B5%E3%80%81%E5%AD%97%E4%B8%B2%E9%80%A3%E6%8E%A5-%E8%AA%9E%E6%B3%95-concat-substring

篩選或是更新資料的時候,常有需要用到補上字串,或是合併欄位的情況。

這時候使用update table set a=a+b 是不行的,要改用concat ,另外可以用SUBSTRING 來作截字的動作

例如
update table set a=concat(a,b);
update table set a=concat(a,'文字');
SELECT SUBSTRING('Quadratically',5);





參考資料如下

CONCAT(str1,str2,...)

Returns the string that results from concatenating the arguments. May have one or more arguments. If all arguments are non-binary strings, the result is a non-binary string. If the arguments include any binary strings, the result is a binary string. A numeric argument is converted to its equivalent binary string form; if you want to avoid that, you can use an explicit type cast, as in this example:

SELECT CONCAT(CAST(int_col AS CHAR), char_col);

CONCAT() returns NULL if any argument is NULL.

mysql> SELECT CONCAT('My', 'S', 'QL');
-> 'MySQL'
mysql> SELECT CONCAT('My', NULL, 'QL');
-> NULL
mysql> SELECT CONCAT(14.3);
-> '14.3'

SUBSTRING(str,pos), SUBSTRING(str FROM pos), SUBSTRING(str,pos,len), SUBSTRING(str FROM pos FOR len)

The forms without a len argument return a substring from string str starting at position pos. The forms with a len argument return a substring lenstr, starting at position pos. The forms that use FROM are standard SQL syntax. It is also possible to use a negative value for pos. In this case, the beginning of the substring is pos characters from the end of the string, rather than the beginning. A negative value may be used for pos in any of the forms of this function. characters long from string

For all forms of SUBSTRING(), the position of the first character in the string from which the substring is to be extracted is reckoned as 1.

mysql> SELECT SUBSTRING('Quadratically',5);
-> 'ratically'
mysql> SELECT SUBSTRING('foobarbar' FROM 4);
-> 'barbar'
mysql> SELECT SUBSTRING('Quadratically',5,6);
-> 'ratica'
mysql> SELECT SUBSTRING('Sakila', -3);
-> 'ila'
mysql> SELECT SUBSTRING('Sakila', -5, 3);
-> 'aki'
mysql> SELECT SUBSTRING('Sakila' FROM -4 FOR 2);
-> 'ki'

沒有留言: