2

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

需要做的事情:员工打卡时在JSON列中添加一个数组,员工打卡时在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 的更新查询。

4

2 回答 2

2

$.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"}
于 2018-04-29T01:46:40.710 回答
0

尝试使用JSON_ARRAY_APPEND而不是JSON_SET.

手册 - h​​ttps: //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"}')
  )
于 2018-04-28T08:22:28.523 回答