在mysql函数中循环遍历JSON对象

时间:2017-11-13 05:47:08

标签: mysql json

我有一个json对象,其中包含一个帐单下的产品列表。我想为它编写一个mysql函数,它从json读取数据并逐个迭代,并将相同的数据插入到产品和账单表中。

这是我的json对象

    {"billNo":16,"date":"2017-13-11 09:05:01","customerName":"Vikas","total":350.0,"fixedCharges":100,"taxAmount":25.78,"status":paid,"product":[{"productId":"MRR11","categoryId":72,"categoryName":"Parker Pen","cost":200,"quantity":2,"log":{"supplierId":"725","supplierName":"Rihant General Stores"}},{"productId":"MRR12","categoryId":56,"categoryName":"Drawing Books","cost":150,"quantity":3,"log":{"supplierId":"725","supplierName":"Rihant General Stores"}}]}

这里我有一个mysql函数,它从JSON中读取数据

    CREATE DEFINER=`mydb`@`%` FUNCTION `raiseOrder`(dataObject Json) 
    RETURNS bigint(11)
    BEGIN
        DECLARE billNo BIGINT(11) DEFAULT NULL;
        DECLARE customerName VARCHAR(64);
        DECLARE date datetime DEFAULT NOW();
        DECLARE total   Float(12,2);
        DECLARE taxamt Float(12,2);
        DECLARE fixedCharges Float(12,2);

        DECLARE products json;
        DECLARE productId bigint(15) DEFAULT NULL;
        DECLARE categoryId bigint(11);
        DECLARE cost float;
        DECLARE categoryName varchar(64);
        DECLARE quantity int default 0;
        DECLARE supplierId bigint(11);
        DECLARE supplierName varchar(128);


        SET billNo = (SELECT JSON_EXTRACT(dataObject, "$.billNo"));
        SET customerName = (SELECT JSON_EXTRACT(dataObject, "$.customerName"));
        SET products = (SELECT JSON_EXTRACT(dataObject, "$.products"));        
        SET productId = (SELECT JSON_EXTRACT(products, "$[0].productId"));      
    RETURN 1;
    END

现在有这些行

    SET products = (SELECT JSON_EXTRACT(dataObject, "$.products"));        
    SET productId = (SELECT JSON_EXTRACT(products, "$[0].productId"));      

我得到内部产品json和第0个产品的id。但我想要一种迭代产品阵列的方法。

1 个答案:

答案 0 :(得分:7)

您可以将WHILE循环与JSON_LENGTH结合使用来实现此目的:

DECLARE json, products, product VARCHAR(4000);
DECLARE i INT DEFAULT 0;
SELECT '{"billNo":16,"date":"2017-13-11 09:05:01","customerName":"Vikas","total":350.0,"fixedCharges":100,"taxAmount":25.78,"status":"paid","product":[{"productId":"MRR11","categoryId":72,"categoryName":"Parker Pen","cost":200,"quantity":2,"log":{"supplierId":"725","supplierName":"Rihant General Stores"}},{"productId":"MRR12","categoryId":56,"categoryName":"Drawing Books","cost":150,"quantity":3,"log":{"supplierId":"725","supplierName":"Rihant General Stores"}}]}
' INTO json;

SELECT json->"$.product" INTO products;

WHILE i < JSON_LENGTH(products) DO
    SELECT JSON_EXTRACT(products,CONCAT('$[',i,']')) INTO product;
    SELECT product;
    SELECT i + 1 INTO i;
END WHILE;

你可能需要做的不仅仅是“选择产品”; - )

注意:MySQL JSON函数已添加到5.7.8中,因此您需要先检查MySQL版本。