MySQL JSON列添加新数组作为元素

时间:2018-04-28 05:51:58

标签: mysql mysql-json

我有一个带有JSON类型列的表,我想用现有JSON中的新数组元素更新一列。

需要做什么:当员工punch_in时在JSON列中添加一个数组,并在员工punch_out时在JSON列中添加另一个数组。

{"emp_sheet":[{"rulecode":"PUNCH_IN","result":1,"applytime":"2018-04-12 04:50:39"},{"rulecode":"PUNCH_OUT","result":1,"applytime":"2018-04-12 13:01:39"}]}

我做了什么,为员工punch_in:

UPDATE table 
SET rule_codes = JSON_SET(COALESCE(rule_codes, '{}'), '$.emp_sheet', '{"rulecode":"PUNCH_IN","result":1,"applytime":"2018-04-12 04:50:39"}') 
WHERE emp_id = 1

结果在rule_codes列=

{"emp_sheet": "{"rulecode":"PUNCH_IN","result":1,"applytime":"2018-04-12 04:50:39"}"}

请帮我写一下员工punch_out的更新查询。

2 个答案:

答案 0 :(得分:1)

如果您在插入时$.emp_sheet创建了一个JSON数组,这将是最简单的:

UPDATE table3
SET rule_codes = JSON_SET(COALESCE(rule_codes, JSON_OBJECT('emp_sheet', JSON_ARRAY())), 
                          '$.emp_sheet[0]', 
                          '{"rulecode":"PUNCH_IN","result":1,"applytime":"2018-04-12 04:50:39"}') 
WHERE emp_id = 1

然后在打卡时,您可以向数组中添加另一个元素:

UPDATE table3
SET rule_codes = JSON_SET(COALESCE(rule_codes, JSON_OBJECT('emp_sheet', JSON_ARRAY())),
                          '$.emp_sheet[1]',
                          '{"rulecode":"PUNCH_OUT","result":1,"applytime":"2018-04-12 13:01:39"}') 
WHERE emp_id = 1;

SELECT rule_codes FROM table3 WHERE emp_id = 1

输出:

{"emp_sheet": [
    "{\"rulecode\":\"PUNCH_IN\",\"result\":1,\"applytime\":\"2018-04-12 04:50:39\"}", 
    "{\"rulecode\":\"PUNCH_OUT\",\"result\":1,\"applytime\":\"2018-04-12 13:01:39\"}"
 ]}

请注意,当您执行SET时,输入JSON('{"rulecode ... }')将被视为字符串,因此上面的输出中的转义"。您可以在提取时删除JSON_UNQUOTE的那些。

SELECT JSON_UNQUOTE(JSON_EXTRACT(rule_codes, '$.emp_sheet[0]')) FROM `table3` 

或使用快捷符号

SELECT rule_codes->>'$.emp_sheet[0]' FROM `table3` 

输出:

{"rulecode":"PUNCH_IN","result":1,"applytime":"2018-04-12 04:50:39"}

答案 1 :(得分:0)

尝试使用JSON_ARRAY_APPEND代替JSON_SET

手动 - https://dev.mysql.com/doc/refman/8.0/en/json-modification-functions.html

我认为它可能就像这样

rule_codes = JSON_ARRAY_APPEND(COALESCE(rule_codes, '{"emp_sheet":[]}'), '$.emp_sheet', '{"rulecode":"PUNCH_IN","result":1,"applytime":"2018-04-12 04:50:39"}')

rule_codes = IF(rule_codes IS NULL,'
    '{"emp_sheet":[{"rulecode":"PUNCH_IN","result":1,"applytime":"2018-04-12 04:50:39"}]}',
    JSON_ARRAY_APPEND(rule_codes, '$.emp_sheet', '{"rulecode":"PUNCH_IN","result":1,"applytime":"2018-04-12 04:50:39"}')
  )