我有两个表主题和评估主题表是具有ID和名称的基本表,并且在评估表中有一个名为topic_list的json列,存储主题数组,我需要具有ID的特定评估的主题列表和名字
CREATE TABLE `topics` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL COMMENT 'topic name will capture here',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=latin1
CREATE TABLE `assessments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`topic_list` json DEFAULT NULL,
`assessment_name` varchar(150) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=latin1
INSERT INTO `topics` (name) values ('topic1'),('topic2'),('topic3');
INSERT INTO `assessments` (topic_list, assessment_name) values ('[1,2]','assessment1'),('[2,3]', 'assessment2'),('[1,3]', 'assessment3');
SELECT t1.id,t1.name FROM topics AS t1 WHERE id IN (SELECT topic_list FROM assessments WHERE id = 1)
这是我尝试过的,但只是获得第一行
SELECT id,name from topics where id in(select JSON_UNQUOTE(TRIM(TRAILING ']' FROM TRIM(LEADING '[' FROM JSON_EXTRACT(topic_list, '$[*]')))) from assessments where id = 1)
我得到的是
1 topic1
结果仅是数组的第一列
我正在尝试
1 topic1
2 topic2
答案 0 :(得分:1)
您可以通过JSON_EXTRACT
和JSON_CONTAINS
使用以下解决方案:
SELECT id, name
FROM topics WHERE (
SELECT JSON_CONTAINS(
JSON_EXTRACT(topic_list, '$[*]'),
CONVERT(topics.id, JSON)
) FROM assessments WHERE id = 1
);