目前我正在寻找一种解决方法来“切出一个varchar的字符串”。从varchar中挑选一个字符串MySQL,存储过程
我有一个游标,它贯穿我从SQL语句中获得的所有行。 在每一行中都包含一个'#',这个我想切出并插入到另一个表中。
但是我怎样才能把'#'和后面的字符切掉?
我想过分裂,但没有找到解决方案如何在MySQL中做到这一点。
我希望你能帮助我
目前我正在寻找一种解决方法来“切出一个varchar的字符串”。从varchar中挑选一个字符串MySQL,存储过程
我有一个游标,它贯穿我从SQL语句中获得的所有行。 在每一行中都包含一个'#',这个我想切出并插入到另一个表中。
但是我怎样才能把'#'和后面的字符切掉?
我想过分裂,但没有找到解决方案如何在MySQL中做到这一点。
我希望你能帮助我
假设你有一个字符串像first #second third
,你可以使用MySQL的字符串函数提取second
:
SUBSTRING(SUBSTRING(col, INSTR(col, '#') + 1),
1,
INSTR(SUBSTRING(col, INSTR(col, '#') + 1), ' ') - 1)
这是假设只有一个井号(#
),并且要提取的字符串结尾的分隔符是空格。
感谢您的回复,但是当一行中有更多标签时?我该如何处理? –
你甚至可以描述你将如何确定_which_ hashtag是你想要的逻辑吗?我会说,如果它看起来太复杂,你可能会更好地将数据读入你的应用层并在那里提取它。 –
不,我不想要“一个”,当有更多的hashtags在这个varchar我想全部切出。在此之后,我会将它们添加到新表格中。 –
这里是和示例功能来在B做
delimiter //
CREATE DEFINER=`root`@`localhost` FUNCTION `cut`(`instring` varchar(255))
RETURNS varchar(255) CHARSET latin1
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
begin
declare tempstring varchar(100);
declare outstring varchar(100);
declare checkit int;
declare firsthashpos int;
declare tempid int;
set tempstring = ltrim(rtrim(instring));
set checkit = 0;
if instr(tempstring,'#') then set firsthashpos = instr(tempstring,'#'); end if;
looper: while tempstring is not null and instr(tempstring,'#') > 0 do
set outstring = reverse(substring(reverse(tempstring),1,instr(reverse(tempstring),'#')));
set tempstring = replace(tempstring,reverse(substring(reverse(tempstring),1,instr(reverse(tempstring),'#'))),'');
insert into b (address) values (outstring);
end while;
return concat(tempstring);
end//
delimiter ;
给这个
select * from a;
+------+---------------------+
| id | address |
+------+---------------------+
| 1 | 13 #ont 12#45 st |
| 2 | 13 #ont 12345 st |
| 3 | 13 #ont 12#45 45678 |
| 4 | 56789 #ont 12#45 st |
+------+---------------------+
结果
从
select id,address,cut(address)
from a
where instr(address,'#') > 0;
结果
select * from b;
+----+---------------+
| id | address |
+----+---------------+
| 1 | #45 st |
| 2 | #ont 12 |
| 3 | #ont 12345 st |
| 4 | #45 45678 |
| 5 | #ont 12 |
| 6 | #45 st |
| 7 | #ont 12 |
+----+---------------+
函数的返回值(outstring)包含#s被移除后的位后留下的内容。希望函数中的字符串操作是不言自明的。
哈哈谢谢,但我决定在php中做这个东西:) –
你可以使用字符串函数,但逻辑会有点复杂。 –