Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

php - check if a value exists in json encode array in mysql

I am working on a Mysql trigger to do something on my database. Before any thing, I want to check if a value exists in a json_encode string in my config table and after that proceed to run the trigger. my config table is handled by php scripts and looks like this:

-------------------------------------------
| config_name | config_value              |
-------------------------------------------
| target_id   | ["1","16","18","22","37"] |
-------------------------------------------

in php we can use: if in_array(json_decode(config_value)) and ...

but my problem is in Mysql syntax which doesn't support in_array and json_decode

How can I check if my value exists in 'config value' in Mysql trigger?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How to solve this problem

If you are storing JSON in mysql, make sure that you upgrade to mysql 5.7, then you can make use of the range of JSON functions available. In your particular case, you can do

   SELECT * FROM my_table WHERE JSON_SEARCH(config_value,"one", "17") IS NOT NULL;

What you Definitely ought to be doing

You have a problem in your data. If you find that you are always searching a JSON field, what that really means is that your table should be normalized.

update: section 2, title changed as suggested by @Sammitch


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...