简体   繁体   中英

How to use SUBSTRING_INDEX in SQLite?

I have this SQL query:

SELECT DISTINCT SUBSTRING_INDEX(value,'_',1) FROM category;

That works with no problems on my MySQL database.

I tried to use it with my SQLite database but it gives me error about SUBSTRING_INDEX command. So, I used this query:

SELECT DISTINCT substr(value,'_',1) FROM category;

This returns an empty result set. Then, I tried this query:

SELECT DISTINCT value FROM category

This worked well. What could be the problem?

Of course this is very late, but for others that may see this question, let me put this here.

The sqlite substr function does not work that way.

It takes 3 arguments. The first is the string you are searching, while the second and third are both integer numbers.

The second argument denotes the starting index of the substring you want to get and the third parameter denotes the number of characters that your substring will have. If you omit the third argument then the substring will start with the second argument and continue to the end of the supplied string.

Finally note that the indexes are 1 based, ie the leftmost character in your string is at index 1, instead of 0.

More special cases such as when the arguments are negative may be found at

http://www.sqlite.org/lang_corefunc.html

As per: https://sqlite.org/lang_corefunc.html#substr The substr(X,Y,Z) function returns a substring of input string X that begins with the Y-th character and which is Z characters long.

Syntax substr( string, start, length )

As per: https://sqlite.org/lang_corefunc.html

  1. Descriptions of built-in scalar SQL functions

The instr(X,Y) function finds the first occurrence of string Y within string X and returns the number of prior characters plus 1, or 0 if Y is nowhere found within X.

Please fined below query for case reported:

SELECT DISTINCT
SUBSTR(value, (INSTR(value, '_')+1), (LENGTH(value)-INSTR(value, '_')))
FROM category;

You should not use SUBSTR in the way that you use it. Try writing it like this:

SELECT DISTINCT SUBSTR(value,'_', 2) FROM category;

The best way to use SUBSTR is to set it in the correct way:

SELECT DISTINCT SUBSTR(value,'3', 1) FROM category; // Where 3 represents index from which you want to substring data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM