萬盛學電腦網

 萬盛學電腦網 >> 數據庫 >> mysql教程 >> mysql sql LENGTH,RIGHT,CHAR_LENGTH字符處理函數

mysql sql LENGTH,RIGHT,CHAR_LENGTH字符處理函數

mysql教程 sql LENGTH,RIGHT,CHAR_LENGTH字符處理函數


LENGTH(str)
 
OCTET_LENGTH(str)
 
CHAR_LENGTH(str)
 
CHARACTER_LENGTH(str)
返回字符串str的長度。

mysql> select LENGTH('text');
        -> 4
mysql> select OCTET_LENGTH('text');
        -> 4

mysql> SELECT
    ->    CONCAT(RIGHT(Name, LENGTH(Name) - INSTR(Name, ' ') + 1),
    ->           ', ', LEFT(Name, INSTR(Name, ' ') - 1))
    ->    AS StudentName
    -> FROM Student
    -> ORDER BY StudentName;
+---------------+
| StudentName   |
+---------------+
|  But, Cory    |
|  Harvests, JJ |
|  Wang, Joe    |
+---------------+
3 rows in set (0.04 sec)


*/

RIGHT(str,len)
返回字符串str的最右面len個字符。
mysql> select RIGHT('foobarbar', 4);
        -> 'rbar'

該函數是多字節可靠的

 

/* Prepare the data */
DROP TABLE Student;

CREATE TABLE Student (
   StudentID INT NOT NULL PRIMARY KEY,
   Name      VARCHAR(50) NOT NULL
)TYPE = InnoDB;


/* Insert data for testing */
INSERT INTO Student (StudentID,Name) VALUES (1,'Joe Wang');
INSERT INTO Student (StudentID,Name) VALUES (2,'Cory But');
INSERT INTO Student (StudentID,Name) VALUES (3,'JJ Harvests');

Select * from StudentExam;

 
/* Real command */
SELECT
   CONCAT(RIGHT(Name, LENGTH(Name) - INSTR(Name, ' ') + 1),
          ', ', LEFT(Name, INSTR(Name, ' ') - 1))
   AS StudentName
FROM Student
ORDER BY StudentName;

 

注意,對於多字節字符,其CHAR_LENGTH()僅計算一次。

 

SELECT Name, CHAR_LENGTH(Name) AS CharLength
FROM DVDs
WHERE CHAR_LENGTH(Name)>5
ORDER BY Name;
copyright © 萬盛學電腦網 all rights reserved