json,返回1个(共3个)部门,列出所有员工

camsedfj  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(335)

在department表中,我有两个字段:

documentid, which is INT
jsondocument which is 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 Johnson",
"empphone":"465-8546",
"empemail":["ojohnson@gmail.com","ojohnson@company.com"]}
]}} ' );

使用相同的查询,我又添加了两个部门,每个部门有3名员工。在db小提琴上演示。我只想返回一个部门并列出所有员工,因此如下所示:
部门名称|员工
“市场营销”|“玛丽·琼斯、汤姆·罗宾逊、奥利维亚·Json”(引号的位置无关紧要)
但我能找到的最接近的是这个查询,它列出了所有部门,每个部门只有第一个员工:

select
    jsondocument->'$.department.deptname' as deptname, 
    jsondocument->'$.department.employee[0].empname' as employees
from department;

这是家庭作业--一门初级课程,我已经努力学习到这一点。任何帮助都将不胜感激。

j91ykkif

j91ykkif1#

这是非常简单的,选择所有的名称进行营销

select
    jsondocument->'$.department.deptname' as deptname, 
    jsondocument->'$.department.employee[*].empname' as employees
from department
HAVING deptname = 'Marketing';
deptname    | employees                                       
:---------- | :-----------------------------------------------
"Marketing" | ["Mary Jones", "Tom Robinson", "Olivia Johnson"]

db<>在这里摆弄

i7uaboj4

i7uaboj42#

如果您运行的是mysql 8.0,那么可以使用 json_table() 使不安 employee 数组,然后进行聚合以将所有员工姓名放在一行上。

select 
    d.jsondocument ->> '$.department.deptname' deptname, 
    group_concat(j.empname) employees
from department d
cross join json_table(
    d.jsondocument -> '$.department.employee',
    '$[*]'
    columns(
        empid int path '$.empid',
        empname varchar(100) path '$.empname',
        empphone varchar(20) path '$.empphone',
        empemail json path '$.empemail'
    )
) j
group by d.jsondocument ->> '$.department.deptid', deptname

实际上如果你只需要 empname s、 您可以稍微缩短查询:

select 
    d.jsondocument ->> '$.department.deptname' deptname, 
    group_concat(j.empname) employees
from department d
cross join json_table(
    d.jsondocument -> '$.department.employee',
    '$[*]'
    columns(empname varchar(100) path '$.empname')
) j
group by d.jsondocument ->> '$.department.deptid', deptname

db小提琴演示:

deptname  | employees                             
:-------- | :-------------------------------------
Marketing | Mary Jones,Tom Robinson,Olivia Johnson

相关问题