[英]substring in MySQL
我試圖在MySQL表中插入一個字符串。 但是以下不是我想要的。
select substring_index('3|5|6|asdf asd|6|0|NULL', '|', 1) as first,
substring_index('3|5|6|asdf asd|6|0|NULL', '|', 2) as second,
substring_index('3|5|6|asdf asd|6|0|NULL', '|', 3) as third,
substring_index('3|5|6|asdf asd|6|0|NULL', '|', 4) as forth,
substring_index('3|5|6|asdf asd|6|0|NULL', '|', 5) as fifth
+-------+--------+-------+----------------+------------------+
| first | second | third | forth | fifth |
+-------+--------+-------+----------------+------------------+
| 3 | 3|5 | 3|5|6 | 3|5|6|asdf asd | 3|5|6|asdf asd|6 |
+-------+--------+-------+----------------+------------------
+
我想將5作為第二,6作為第三和'asdf asd'作為第四列。 在MySQL中可以嗎?
substring_index(substring_index('3|5|6|asdf asd|6|0|NULL', '|', 2), '|', -1)
給5
substring_index(substring_index('3|5|6|asdf asd|6|0|NULL', '|', 3), '|', -1)
給6
等等
您可以在定界符上拆分它。 Mysql缺少執行此操作的功能,但是您可以創建一個:
create function split_string(stringy varchar(128), lim varchar(3),posi int)
returns varchar(255)
return replace(substring(substring_index(stringy, lim, posi),
length(substring_index(stringy, lim, posi -1)) + 1), lim, '');
為簡單起見,我們將var設置為'3 | 5 | 6 | asdf asd | 6 | 0 | NULL'...
set @cow='3|5|6|asdf asd|6|0|NULL';
select split_string(@cow,'|',1) as first,split_string(@cow,'|',2) as second,
split_string(@cow,'|',3) as third,split_string(@cow,'|',4) as fourth,
split_string(@cow,'|',5) as fifth,split_string(@cow,'|',6) as sixth;
在我看來,您似乎缺少指定要獲取子字符串的索引,因此您總是從原始字符串的開頭開始。 我不太熟悉mysql語法,但是請檢查substring_index函數是否支持此功能。
SUBSTRING_INDEX(str,delim,count)在出現定界符delim之前從字符串str返回子字符串。 如果count為正,則返回最后定界符左側的所有內容(從左側開始計數)。 如果count為負,則返回最后定界符右邊的所有內容(從右邊開始計數)。 搜索delim時,SUBSTRING_INDEX()執行區分大小寫的匹配。
mysql> SELECT SUBSTRING_INDEX('www.mysql.com','。',2); ->'www.mysql'mysql> SELECT SUBSTRING_INDEX('www.mysql.com','。',-2); ->'mysql.com'此功能是多字節安全的。 從這里
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.