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

MySQL JSON column add new array as element

我有一个 table 类型为 JSON 的列,我想用现有 JSON.

中的新数组元素更新一个列

需要做的事情:员工punch_in时在JSON列添加一个数组,员工punch_in时在JSON列添加另一个数组员工 punch_out.

{"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 的更新查询。

尝试使用 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"}')
  )

如果你在打卡时制作 $.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"}