[英]MySql Trimming characters till a space
如何修剪(刪除)從字符串右邊到第一個空格的所有字符?
這是我想做的事情:
set @s:='May the Gods watch over your battles, my friend!';
select if(length(@s) < 10,@s,left(@s,10)) a;
#output from above: 'May the Go'
#desired output: 'May the'
為了避免像May the Go
這樣的奇怪輸出,我嘗試從右到第一個空格修剪所有字符,因此輸出為May the
。
如何在sql語句本身中完成此操作。 我找不到可以執行此操作的內置函數?
這在Microsoft SQL中有效,如果用INSTR替換CHARINDEX則應該有效
select substring(@s,1,charindex(' ',reverse(@s)))
在下面添加了我的SQL Fiddle版本,其工作方式與Microsoft SQL有所不同
http://sqlfiddle.com/#!2/d41d8/44718
select @s,left(@s,10-locate(' ',reverse(@s)));
數據庫中的示例
select theFld,
CASE
WHEN length(theFld) <= 20 THEN theFld
ELSE
left(theFld,20-locate(' ',reverse(left(theFld,20))))
END as Abbr
FROM example;
您可以這樣嘗試:
.....
.....
--define max length for the extracted text
set @length:=10;
set @result =
--check if either the last extracted character or...
--the character next to the last is a space (or both are spaces)
if(substring(@s, @length, 2) LIKE '% %',
--if true, extract using simple left()'
left(@s,@length),
--else, use the same simple left() operation then remove all characters..
--starting from the right-most until the first space found
replace(left(@s,@length), substring_index(left(@s, @length), ' ', -1), '')
);
[ SQL Fiddle演示 ]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.