在 MySQL 5.7 中,如何在 json 字段上使用 JOIN 来实现关联查询?

1、现有表 theme_table1 ,其中字段 theme_table2_ids 为 json 类型,值为数组,数组中的值关联了表 theme_table2 的主键ID。如图1

图1

2、之前编写过查询某一条 theme_table2 中的 id 是否存在于表 theme_table1 中。SQL 实现如下

select * from `theme_table1` where json_contains(`theme_table2_ids`, '391') limit 1

3、现在需要查询出有哪些表 theme_table2 中的记录存在于 表 theme_table1 的 字段 theme_table2_ids 中。SQL 实现如下,如图2

图2

SELECT
 `theme_table1`.theme_table2_ids,
 `theme_table2`.id,
 `theme_table2`.processing,
 `theme_table2`.processing_failed 
FROM
 `theme_table1`
 INNER JOIN `theme_table2` ON JSON_CONTAINS(
  `theme_table1`.theme_table2_ids,
 CONVERT ( `theme_table2`.id, CHAR )) = 1 
WHERE
 `processing` = 0 
 AND `processing_failed` = 1
永夜