首页 > 解决方案 > Mysql加入json值问题

问题描述

我在 mysql 5.7 服务器上有以下表格

produit__parure

id_parure (int) ids_produits_parure (json)
21 [“34809”、“34823”、“34813”]
22 [“35703”、“35854”、“35877”]

produit

id_product (int) ...其他列
34809 ...
34810 ...

我尝试使用以下查询在 id.prod = value 上加入 ids_produits_parure :

SELECT p.id_prod, pp.* FROM produit p left JOIN produit__parure pp on
JSON_CONTAINS(pp.ids_produits_parure->'$[*]', CAST(p.id_prod as JSON))
where id_prod=34809

但它在 produit__parure 文件上返回 NULL:

id_prod id_parure ids_produits_parure
34809 无效的 无效的

我究竟做错了什么?结果我想要的是:

id_prod id_parure ids_produits_parure
34809 21 [“34809”、“34823”、“34813”]

我尝试了 Dan Chase 的答案,但它产生了错误的结果(我的行 ids_produits_parure 不等于 id_prod )

id_prod id_parure ids_produits_parure
34809 21 [“34809”、“34823”、“34813”]
34809 22 [“35703”、“35854”、“35877”]

标签: mysqlmysql-json

解决方案


您是否可能仅在 JSON_CONTAINS 上选择 ID 作为 JSON?我不知道生成的代码应该是什么样子,除了可能类似的东西:

JSON_CONTAINS(pp.ids_produits_parure->'$[*]', CAST(pp as JSON))

因为我怀疑ID是一个数组,你不会搜索pp而不是p吗?

参考: https ://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html#:~:text=JSON_CONTAINS%20%28target%2C%20candidate%20%5B%2C%20path %20%5D%29%20表示%20by,找到%20at%20a%20特定%20path%20within%20the%20target。


推荐阅读