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?
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;
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
using this:
@Query(value = "select * from configs where json_contains(config_value, json_array(?1))))", nativeQuery = true)
List<Config> list(String config);
Okay so what you have there is a JSON_ARRAY()
to check if a particular id exists in the JSON_ARRAY()
simply put a condition ie JSON_CONTAINS(config_value,"1")=1
, so if "1" is present in the your JSON_ARRAY() then it will return 1 else 0.
Also, rather than doing json_encode in PHP code while doing the insert/update query you could use "..config_value=JSON_ARRAY(" . implode(',', $arr) . ") ...
Thanks for your reply. But unfortunately mysql version is 5.1 and it's impossible to upgrade it. Actually I am adding some features to a voipswitch system. So my flexibility is limited to the present features.
I am selecting multiple tariffs and I want to record inserted calls (after insert calls in the 'calls' table via my trigger) which belong to the selected tariffs in a list for some analyses.
Also I tried php serialize function instead of json_encode to store my tariff id's in config table. But mysql doesn't support unserialize as well.
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.