![](/img/trans.png)
[英]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.