mysql json列添加新数组作为元素

hl0ma9xz  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(365)

我有一个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"}]}

我所做的,为员工打卡:

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

规则代码列中的结果= {"emp_sheet": "{"rulecode":"PUNCH_IN","result":1,"applytime":"2018-04-12 04:50:39"}"} 请帮我写员工打卡的更新查询。

mftmpeh8

mftmpeh81#

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

zbq4xfa02#

这将是最容易的,如果你做的 $.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\"}"
 ]}

注意,当您进行设置时,输入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"}

相关问题