从单个MySQL 选择查询中检索来自两个连接表的所有信息的最佳和最优雅的方法是什么,但是以分层的方式?
我有这两张桌子:
----------------- ------------------
| Table COMPANY | | Table EMPLOYEE |
----------------- ------------------
| id | | id |
| companyName | | companyId |
----------------- | employeeName |
------------------
(for each company, many employees)
我想输出以下分层 JSON 片段:
[
{"id": 1,
"companyName": "Company A",
"employees": [
{"id": 1, "employeeName": "Employee 1"},
{"id": 2, "employeeName": "Employee 2"}
]},
{"id": 2,
"companyName": "Company B",
"employees": [
{"id": 3, "employeeName": "Employee 3"},
{"id": 4, "employeeName": "Employee 4"}
]}
]
“解决方案”1:
对连接的表进行全选,并在创建 json 片段后编写一些代码:
select * from company, employee where employee.companyId = company.id;
问题:我留下了很多丑陋的 foreach 类型代码来创建 json 片段
“解决方案”2:
按公司所有员工在 json 字符串中分组:
select company.id, company.name,
concat('[',
group_concat('{"id": ', employee.id, ',
"employeeName": "', employee.employeeName,'"}'), ']') as employees
from company, employee where company.id = employee.companyId
group by company.id
这里,“employees”已经是一个json片段,我只需要jsonify company.id和name即可。但是在 mysql 中构建 json 片段似乎是非常糟糕的做法。
任何见解或其他解决方案?
非常感谢