我正在使用MySQL 5.7。我有一个带有JSON列的表。
MySQL [test_db]> select * from mytable;
+----+-------+---------------------+
| id | name | hobby |
+----+-------+---------------------+
| 1 | Rahul | {"Game": "Cricket"} |
| 2 | Sam | null |
+----+-------+---------------------+
在这里,对于行id = 2,我想插入一个数据。我做到了-
update mytable set hobby = JSON_SET(hobby, '$.Game', 'soccer') where id = 2;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0
似乎已正确插入数据,但是当我检查
MySQL [test_db]> select * from mytable;
+----+-------+---------------------+
| id | name | hobby |
+----+-------+---------------------+
| 1 | Rahul | {"Game": "Cricket"} |
| 2 | Sam | null |
+----+-------+---------------------+
未插入数据,任何人都可以提供一些提示,我在这里缺少什么。
谢谢。
答案 0 :(得分:1)
爱好是NULL,并且不能在NULL上设置属性,因此请使用IF语句,首先将null转换为空对象(或将hobby初始化为空对象而不是NULL):
from openpyxl.styles.borders import Border, Side, BORDER_THIN
thin_border = Border(
left=Side(border_style=BORDER_THIN, color='00000000'),
right=Side(border_style=BORDER_THIN, color='00000000'),
top=Side(border_style=BORDER_THIN, color='00000000'),
bottom=Side(border_style=BORDER_THIN, color='00000000')
)
ws.cell(row=3, column=2).border = thin_border
或者,使用COALESCE:
UPDATE mytable
SET hobby = JSON_SET(IF(hobby IS NULL, '{}', hobby), '$.Game', 'soccer')
WHERE id = 2;
请参见dbfiddle here。