2014-10-17 48 views
1
select address (first 20 character) as Address1 , 
     address (characters after first 20 if less then 20 then NULL) as Address2 
from customer 

如何在20個字符後選擇字符串?如何選擇字段後的前20個字符mysql

+0

我想你可能會誤用你的數據庫。這兩個字段應該放在不同的列中,這樣你就不必再做這種事情了。 – OneHoopyFrood 2014-10-17 18:48:05

+2

可能是子串函數。 http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substring – Gohn67 2014-10-17 18:48:33

+0

我將一個表中的值傳遞給另一個地址字段有限制的地方。 – back123 2014-10-17 18:53:08

回答

3

爲了得到第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個字符,你可以使用子功能是這樣的:

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 
+0

謝謝先生.. !! – back123 2014-10-17 19:01:37

2

substring就是你要找的內容:

SELECT SUBSTRING(address, 1, 20) AS Address1, 
     SUBSTRING(address FROM 20) AS Address2 
FROM customer 
+0

感謝您的幫助 – back123 2014-10-17 19:02:13