我有一个名为
posts
columns的表id, title, tags
。CREATE TABLE IF NOT EXISTS `posts` ( `id` int(6) unsigned NOT NULL, `title` varchar(100) NOT NULL, `tags` json NOT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8;
[{"tag": "android", "time": 122}, {"tag": "apple", "time": 140}]
像在tags
字段中一样存储数据。INSERT INTO `posts` (`id`, `title`, `tags`) VALUES ('1', 'First Post', '[{"tag": "andoroid", "time": 123}, {"tag": "mobiles", "time": 432} ]'), ('2', 'Second Post', '[{"tag": "apple", "time": 125}]'), ('3', 'Third Post', '[{"tag": "android", "time": 124}]'), ('4', 'Fourth Post', '[{"tag": "mobiles", "time": 472}, {"tag": "android", "time": 129}]'), ('5', 'Fifth Post', '[{"tag": "android", "time": 122}, {"tag": "apple", "time": 140}]'), ('6', 'Sixth Post', '[{"tag": "mobiles", "time": 121}, {"tag": "apple", "time": 120}]'), ('7', 'Seventh Post', '[{"tag": "apple", "time": 120}, {"tag": "mobiles", "time": 130}]'), ('8', 'Eigth Post', '[{"tag": "android", "time": 126}]'), ('9', 'Nineth Post', '[{"tag": "mobiles", "time":132}]');
根据标签值过滤表中的数据,例如。
tag == "android"
. 为了实现这一点,我正在使用 mysql 查询SELECT id, title, tags FROM posts where JSON_CONTAINS( tags , '{"tag": "android"}' ) ;
它工作正常。DB小提琴:https ://www.db-fiddle.com/f/5Hw1FyL3Qv2RLtCw4tZbyh/1
此外,我需要根据time
tags 中的值订购结果。tag == 'android' and order by time
.
提前感谢您的帮助。