MySql字串函式使用技巧

2022-08-18 07:24:22 字數 1552 閱讀 4249

1、從左開始擷取字串

left(str, length) 

說明:left(被擷取字段,擷取長度) 

例:select left(content,200) as abstract from my_content_t 

2、從右開始擷取字串

right(str, length) 

說明:right(被擷取字段,擷取長度) 

例:select right(content,200) as abstract from my_content_t 

3、擷取字串 

substring(str, pos) 

substring(str, pos, length) 

說明:substring(被擷取字段,從第幾位開始擷取) 

substring(被擷取字段,從第幾位開始擷取,擷取長度) 

例:select substring(content,5) as abstract from my_content_t 

select substring(content,5,200) as abstract from my_content_t 

(注:如果位數是負數 如-5 則是從後倒數字數,到字串結束或擷取的長度) 

4、按關鍵字擷取字串

substring_index(str,delim,count) 

說明:substring_index(被擷取字段,關鍵字,關鍵字出現的次數) 

例:select substring_index("blog.jb51.net","。",2) as abstract from my_content_t 

結果:blog.jb51 

(注:如果關鍵字出現的次數是負數 如-2 則是從後倒數,到字串結束) 

5、instr(str,substr) ;locate(str,substr); position(str in substr)

返回子串substr在字串str中的第乙個出現的位置。這與有2個引數形式的locate()相同,除了引數被顛倒。 

6、reverse(str)

反轉str; 

7、truncate(x,d);

返回被捨去至小數點後d位的數字x。若d 的值為 0, 則結果不帶有小數點或不帶有小數部分。可以將d設為負數,若要截去(歸零) x小數點左起第d位開始後面所有低位的值.

今天正好有個需求,查詢標準表中某2個字段的百分比....

示例:

select truncate(progress/video_duration,2) as percent  from mime_study_logs ;

video_duration欄位即使(這裡的分母為0或null),返回的也是null,而不用php計算驗證除法的合法性
這裡計算了兩個數相除,2表示結果小數點後面的位數,比如:1/3 =0.33

mysql字串函式使用解析

最近使用的相關字串查詢有 源資料有 1,查詢字串長度 select length name from temp 返回結果如下 2,查詢某乙個字串在目標字串位置 select locate o name from temp 返回結果,目標字串從左開始第一次出現的位置 3,從左邊開始,擷取長度為某個值的...

mysql字串邊界 mysql字串函式

mysql 字串擷取函式 ord cast left right substring substring index mid substr 其中,mid substr 等價於substring 函式,substring 的功能非常強大和靈活。ord 用於返回字串第乙個字元的ascii碼。cast 1...

mysql 字串函式

注意以下 sql 均在 putty 下執行,所以對中文的支援不好 當輸入的中文字符集是 big5 而要求儲存的是 utf8,而putty 只支援簡體中文 或者其他特殊情況時.select menu name cn from menu item where menu id 23 menu name c...