简体   繁体   English

带有JSON数组的MYSQL REGEXP

[英]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. 我有一个存储在数据库中的JSON字符串,我需要根据JSON字符串中的WHERE条件进行SQL COUNT。 I need it to work on the MYSQL 5.5. 我需要它才能在MYSQL 5.5上工作。

The only solution that I found and could work is to use the REGEXP function in the SQL query. 我发现并可以使用的唯一解决方案是在SQL查询中使用REGEXP函数。

Here is my JSON string stored in the custom_data column: 这是我存储在custom_data列中的JSON字符串:

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

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

I now need to create a SQL sentence: 我现在需要创建一个SQL语句:

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. 我寻找的条件是language_display必须为1、2或3 ...或创建SQL语句时要定义的任何值。

So far I came here with the REGEX expression, but it does not work: 到目前为止,我来到这里的是REGEX表达式,但是它不起作用:

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

Where 1 is replaced with the value that I look for. 其中1替换为我寻找的值。 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. 通常,我也可以寻找“ 1”(带引号),但它也会在meta_display数组中找到,该数组将具有不同的值。

I am not good with REGEX! 我对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. https://regex101.com/是一个免费的在线正则表达式测试仪,它看起来很棒。 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. 即使您想将想法付诸实践,也会像fvck一样慢。 Better off to process through each row once and generate something more easily searched via sql. 更好地处理每一行一次并生成更容易通过sql搜索的内容。 Even a field containing the comma separated list would be better. 甚至包含逗号分隔列表的字段也会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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