[英]Select all records from table 1 then select all records from table 2 matching table 1 primary key
[英]Select all records from relationship table as array based on primary key of "parent" table
我有这些表:
用户:
+----+--------+
| Id | Name |
+----+--------+
| 1 | Name 1 |
| 2 | Name 2 |
+----+--------+
文档组:
+----+-----------------+
| Id | Name |
+----+-----------------+
| 1 | Document name 1 |
| 2 | Document name 2 |
| 3 | Document name 3 |
+----+-----------------+
用户文档组:
+----+---------+--------------+
| Id | User_id | Document_id |
+----+---------+--------------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 2 |
| 4 | 1 | 3 |
+----+---------+--------------+
我希望结果如下所示:
result = [
1, "Name 1", ["Document name 1", "Document name 2", "Document name 3"]
2, "Name 2", ["Document name 2"]
]
问题是我什至不知道如何开始......
目前,我正在解析后端端的大量数据并在那里进行分组/映射(使用 PHP),但我遇到的问题是,对于大型数据集,它需要很多时间(大约 10 秒)...
有没有办法在 MySQL 中创建这样的查询?
也许是这样的?
select
group_concat(concat(users.id, ',', concat('\"',users.name,'\"'), ',',
concat('[',all_documents,']')), ';')
as final_result
from users
join
(
select group_concat(concat('\"',documents.name,'\"'))
as all_documents,users.id
from users_documents, users, documents
where documents.id=users_documents.document_id and
users.id=users_documents.user_id
group by users.id
) temp1 on users.id = temp1.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.