简体   繁体   中英

mysql find_in_set string starting with

I need to search value starting with given string in comma separated values.
Example,
I have '1_2_3_4_5_6, 1_2_3_4_5_8, 1_2_3_6_5_8' in my column. I can search for rows with exact value using
select * from table where find_in_set('1_2_3_4_5_6',column)

But how to search, if starting part of the string is given? something like this:
select * from table where find_in_set('1_2_3%',column) ?

If I understand you correctly (I'm still not sure I do), you could just use:

SELECT * FROM table WHERE column LIKE '%1_2_3%';

This would give you columns where the value is like:

1_2_3_4_5_5
1_4_5_, 1_2_3_4_5_, 6_7

and so on.

But you should really normalize your tables. This is important for good queries and performance wise also important.

According to @Xatenev suggestions, if you really like only the values and the row of each matching row, this won't work so well and will be a lot of overhead. This are the steps that I would perform:

  1. Split all CSV columns into multiple rows (this is a hack and a performance killer, I found some working solution but did not test it, see here ): Pseudo Code: SELECT ID, SPLIT(',', column) AS entries FROM table (NOT WORKING)
  2. Filter the new virtual table to select only rows that match the prefix ( SELECT * FROM virtual_table WHERE find_in_set("1_2_3%, entries) ORDER BY ID )
  3. Concatenate the matching entries back into a list for each ID . eg SELECT ID, GROUP_CONCAT(entries SEPARATOR ', ') FROM filtered_table GROUP BY ID
  4. Do something

The unknown part is the beginning with the split in multiple rows. There are a lot of possible solutions all with their own drawbacks or advantages. Be aware that this will always (regardless of the selected method) will cost a lot of performance.

ADDITIONAL NODE:

It could be adventures in your situation, that you get each row matching your search string like in my first example and filter them in memory. This might be faster than doing this in MYSQL.

you can try with 'REGEXP'

If you want to match data with subtring, please try this

SELECT * FROM `table` WHERE `column` REGEXP '[, ]?1_2_3[^,]*,?' ;

Or

If you want to exact start match, please try this

SELECT * FROM `table` WHERE `column` REGEXP '[, ]?1_2_3[^,]*,?' AND `column` NOT REGEXP '[^, ]1_2_3[^,]*,?' ;

I was able to solve it with no-regex. Sonam's Answer is correct as well.

SELECT * from table WHERE CONCAT(',', columnname, ',') like '%,1_2_3%'

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