Py学习  »  DATABASE

(已解决)Mysql加入json值问题

MicMoz • 3 年前 • 1288 次点击  

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

produit__parure

id_parure(内部) ids_produits_parure(json)
21 ["34809", "34823", "34813"]
22 ["35703", "35854", "35877"]

produit :

id_产品(int) ... 其他专栏
34809 ...
34810 ...

我尝试通过以下查询将id\u produits\u parure上的id.prod=value连接起来:

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_produits_parure
34809 无效的 无效的

我做错了什么? 因此,我想要的是:

id_prod 身份证 ID_produits_parure
34809 21 ["34809", "34823", "34813"]

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

id_prod 身份证 ID_produits_parure
34809 21 ["34809", "34823", "34813"]
34809 22 ["35703", "35854", "35877"]
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130410
 
1288 次点击  
文章 [ 2 ]  |  最新文章 3 年前
nbk
Reply   •   1 楼
nbk    4 年前

你的KSON_包含有点。

Json在大多数情况下都很难处理,因此您应该考虑切换到规范化设计

CREATE TABLE produit__parure
    (`id_parure` int, `ids_produits_parure` json)
;
    
INSERT INTO produit__parure
    (`id_parure`, `ids_produits_parure`)
VALUES
    ('21', '["34809", "34823", "34813"]'),
    ('22', '["35703", "35854", "35877"]')
;
CREATE TABLE produit
    (`id_product` int, `other columns` varchar(3))
;
    
INSERT INTO produit
    (`id_product`, `other columns`)
VALUES
    (34809, '...'),
    (34810, '...')

;

SELECT JSON_CONTAINS(`ids_produits_parure`, CONCAT('"','34809' ,'"'), '$') FROM produit__parure
| JSON_CONTAINS(`ids_produits_parure`, CONCAT('"','34809' ,'"'), '$') |
| ------------------------------------------------------------------: |
|                                                                   1 |
|                                                                   0 |
SELECT p.id_product, pp.* FROM produit p left JOIN produit__parure pp on
JSON_CONTAINS(pp.ids_produits_parure, CONCAT('"',p.id_product,'"'),'$')
where id_product=34809
id_product | id_parure | ids_produits_parure                                   
---------: | --------: | :-----------------------------------------------------
     34809 |        21 | 5b223334383039222c20223334383233222c20223334383133225d

db<>不停摆弄 here

Dan Chase
Reply   •   2 楼
Dan Chase    4 年前

您是否可能只是在JSON_包含的JSON上选择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%20Indicates%20by,found%20at%20a%20specific%20path%20within%20the%20target.