在department表中,我有两个字段:
documentid,即int
json文档,即json
我执行了以下查询:
INSERT INTO department VALUES
(1,'{"department":{
"deptid":"d1",
"deptname":"Marketing",
"deptroom":"Room 7",
"deptphone":["465-8541","465-8542","465-8543"],
"employee":[{
"empid":"e1",
"empname":"Mary Jones",
"empphone":"465-8544",
"empemail":["mjones@gmail.com","mjones@company.com"]},
{
"empid":"e2",
"empname":"Tom Robinson",
"empphone":"465-8545",
"empemail":["trobinson@gmail.com","trobinson@company.com"]},
{
"empid":"e3",
"empname":"Olivia",
"empphone":"465-8546",
"empemail":["ojohnson@gmail.com","ojohnson@company.com"]}
]}} ' );
现在,我尝试使用以下代码返回deptname和deptphone:
SELECT
documentid,
jsondocument->'$.deptname' as deptname,
jsondocument->'$.deptphone' as deptphone
from department;
但是,它返回空值。我哪里出错了?
2条答案
按热度按时间tyky79it1#
基本上,您缺少一级键
department
在json路径中:db小提琴演示:
注意这会给你
deptphone
作为一个json数组-因为这就是它在json文档中的存储方式。如果要将数组取消嵌套到几行中,则需要额外的处理(在mysql 8.0中,通常使用json_table()
)-你可能想问一个新问题。vyu0f0g12#
deptname和deptphone在department内部,因此必须使用.department.deptname而不是.deptname,与.deptphone相同,它将是.department.deptphone