mysql 截取指定的兩個字符串之間的內(nèi)容_MySQL
Jun 01, 2016 pm 01:19 PMbitsCN.com
如 現(xiàn)有字符串 "[]aseabcd[12345]ddxabcdsx[]",要截取"abcd[" 和 "abcd["之后的第一個 "]" 之間的內(nèi)容 "12345",當(dāng)然當(dāng)中的內(nèi)容長度不是固定的,可以是"123456" 或者其他字符串。
他問我的時候,我第一反應(yīng)就是想的indexOf,后來查了下 發(fā)現(xiàn)mysql中沒有indexOf 而是 locate。
經(jīng)過半個多小時的嘗試,最好幫他實現(xiàn)了這個效果。
CREATE PROCEDURE sp_str
(
IN p_str VARCHAR(50), /*原始字符串*/
IN p_begin_str VARCHAR(50), /*要匹配的起始字符串*/
IN p_end_str VARCHAR(50)) /*要匹配的結(jié)束字符串*/
OUT p_result VARCHAR(50)) /*返回結(jié)果*/
NOT DETERMINISTIC
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE m_len INT DEFAULT 0;
DECLARE m_index INT DEFAULT 0;
/*計算第一個匹配字符串的索引位置*/
select locate(p_begin_str,p_str)+char_length(p_begin_str) into m_index;
/*計算第一個匹配字符串的長度*/
select locate(p_end_str,p_str,m_index) into m_len;
select SUBSTRING(p_str,m_index,m_len-m_index) INTO p_result ;
END;
執(zhí)行:
CALL sp_str('[]abcd[12345]aa[]ss','abcd[',']',@result);
返回值 @result 為12345
call sp_str('[]abcd[sdww]aa[]ss','abcd[',']',@result);
返回值 @result 為sdww
如果不用存儲過程,可以直接寫sql語句實現(xiàn):
如:
select SUBSTRING(
']abcd[12345]111[]',
locate('abcd[',']abcd[12345]111[]')+CHAR_LENGTH('abcd['),
locate(']',']abcd[12345]111[]',CHAR_LENGTH('abcd['))-
(select locate('abcd[',']abcd[12345]111[]')+CHAR_LENGTH('abcd['))
)
返回值為 12345
關(guān)于mysql的函數(shù)介紹:
CHAR_LENGTH(str)
返回字符串str的長度。
LOCATE(substr,str)
POSITION(substr IN str)
返回子串substr在字符串str第一個出現(xiàn)的位置,如果substr不是在str里面,返回0.
mysql> select LOCATE('bar', 'foobarbar');
-> 4
mysql> select LOCATE('xbar', 'foobar');
-> 0
該函數(shù)是多字節(jié)可靠的。 LOCATE(substr,str,pos)
返回子串substr在字符串str第一個出現(xiàn)的位置,從位置pos開始。如果substr不是在str里面,返回0。
mysql> select LOCATE('bar', 'foobarbar',5);
-> 7
這函數(shù)是多字節(jié)可靠的。
SUBSTRING(str,pos,len)
SUBSTRING(str FROM pos FOR len)
MID(str,pos,len)
從字符串str返回一個len個字符的子串,從位置pos開始。使用FROM的變種形式是ANSI SQL92語法。
mysql> select SUBSTRING('Quadratically',5,6);
-> 'ratica'
該函數(shù)是多字節(jié)可靠的。
SUBSTRING(str,pos)

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

mysqldump is a common tool for performing logical backups of MySQL databases. It generates SQL files containing CREATE and INSERT statements to rebuild the database. 1. It does not back up the original file, but converts the database structure and content into portable SQL commands; 2. It is suitable for small databases or selective recovery, and is not suitable for fast recovery of TB-level data; 3. Common options include --single-transaction, --databases, --all-databases, --routines, etc.; 4. Use mysql command to import during recovery, and can turn off foreign key checks to improve speed; 5. It is recommended to test backup regularly, use compression, and automatic adjustment.

You can use substr() or mb_substr() to get the first N characters in PHP. The specific steps are as follows: 1. Use substr($string,0,N) to intercept the first N characters, which is suitable for ASCII characters and is simple and efficient; 2. When processing multi-byte characters (such as Chinese), mb_substr($string,0,N,'UTF-8'), and ensure that mbstring extension is enabled; 3. If the string contains HTML or whitespace characters, you should first use strip_tags() to remove the tags and trim() to clean the spaces, and then intercept them to ensure the results are clean.

There are two main ways to get the last N characters of a string in PHP: 1. Use the substr() function to intercept through the negative starting position, which is suitable for single-byte characters; 2. Use the mb_substr() function to support multilingual and UTF-8 encoding to avoid truncating non-English characters; 3. Optionally determine whether the string length is sufficient to handle boundary situations; 4. It is not recommended to use strrev() substr() combination method because it is not safe and inefficient for multi-byte characters.

MySQL supports transaction processing, and uses the InnoDB storage engine to ensure data consistency and integrity. 1. Transactions are a set of SQL operations, either all succeed or all fail to roll back; 2. ACID attributes include atomicity, consistency, isolation and persistence; 3. The statements that manually control transactions are STARTTRANSACTION, COMMIT and ROLLBACK; 4. The four isolation levels include read not committed, read submitted, repeatable read and serialization; 5. Use transactions correctly to avoid long-term operation, turn off automatic commits, and reasonably handle locks and exceptions. Through these mechanisms, MySQL can achieve high reliability and concurrent control.

To view the size of the MySQL database and table, you can query the information_schema directly or use the command line tool. 1. Check the entire database size: Execute the SQL statement SELECTtable_schemaAS'Database',SUM(data_length index_length)/1024/1024AS'Size(MB)'FROMinformation_schema.tablesGROUPBYtable_schema; you can get the total size of all databases, or add WHERE conditions to limit the specific database; 2. Check the single table size: use SELECTta

Character set and sorting rules issues are common when cross-platform migration or multi-person development, resulting in garbled code or inconsistent query. There are three core solutions: First, check and unify the character set of database, table, and fields to utf8mb4, view through SHOWCREATEDATABASE/TABLE, and modify it with ALTER statement; second, specify the utf8mb4 character set when the client connects, and set it in connection parameters or execute SETNAMES; third, select the sorting rules reasonably, and recommend using utf8mb4_unicode_ci to ensure the accuracy of comparison and sorting, and specify or modify it through ALTER when building the library and table.

To set up asynchronous master-slave replication for MySQL, follow these steps: 1. Prepare the master server, enable binary logs and set a unique server-id, create a replication user and record the current log location; 2. Use mysqldump to back up the master library data and import it to the slave server; 3. Configure the server-id and relay-log of the slave server, use the CHANGEMASTER command to connect to the master library and start the replication thread; 4. Check for common problems, such as network, permissions, data consistency and self-increase conflicts, and monitor replication delays. Follow the steps above to ensure that the configuration is completed correctly.

The most direct way to connect to MySQL database is to use the command line client. First enter the mysql-u username -p and enter the password correctly to enter the interactive interface; if you connect to the remote database, you need to add the -h parameter to specify the host address. Secondly, you can directly switch to a specific database or execute SQL files when logging in, such as mysql-u username-p database name or mysql-u username-p database name
