简体   繁体   中英

MYSQL REGEXP with JSON array

I have an JSON string stored in the database and I need to SQL COUNT based on the WHERE condition that is in the JSON string. I need it to work on the MYSQL 5.5.

The only solution that I found and could work is to use the REGEXP function in the SQL query.

Here is my JSON string stored in the custom_data column:

{"language_display":["1","2","3"],"quantity":1500,"meta_display:":["1","2","3"]}

https://regex101.com/r/G8gfzj/1

I now need to create a SQL sentence:

SELECT COUNT(..) WHERE custom_data REGEXP '[HELP_HERE]'

The condition that I look for is that the language_display has to be either 1, 2 or 3... or whatever value I will define when I create the SQL sentence.

So far I came here with the REGEX expression, but it does not work:

(?:\"language_display\":\[(?:"1")\])

Where 1 is replaced with the value that I look for. I could in general look also for "1" (with quotes), but it will also be found in the meta_display array, that will have different values.

I am not good with REGEX! Any suggestions?

I used the following regex to get matches on your test string

\"language_display\":\[(:?\"[0-9]\"\,)*?\"3\"(:?\,\"[0-9]\")*?\]

https://regex101.com/ is a free online regex tester, it seems to work great. Start small and work big.

Sorry it doesn't work for you. It must be failing on the non greedy '*?' perhaps try without the '?'

Have a look at how to serialize this data, with an eye to serializing the language display fields. How to store a list in a column of a database table

Even if you were to get your idea working it will be slow as fvck. Better off to process through each row once and generate something more easily searched via sql. Even a field containing the comma separated list would be better.

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