[英]Mysql - Single Query for One-To-Many
I have a table named posts
and another table named attachments
... 我有一个名为
posts
的表和另一个名为attachments
表...
A post
can have many attachments
... post
可以有很多attachments
......
So, I create a middle table called post_attachment
.. 所以,我创建了一个名为
post_attachment
的中间表。
How to get the list of posts
data including the attachments
data in A SINGLE QUERY ? 如何在单一查询中获取
posts
数据列表,包括attachments
数据?
.. ..
Please refer below to make it clearer to understand... 请参阅下面的内容,以便更清楚地了解......
Below are the table structure: 以下是表格结构:
- -
posts
table have 4 columns: posts
表有4列:
- -
attachments
table have 3 columns: attachments
表有3列:
- -
post_attachment
table have 2 columns: post_attachment
表有2列:
Below are the example of a post
that have multiple attachments
以下是具有多个
attachments
的post
的示例
posts
table: posts
表:
- -
attachments
table: attachments
表:
- -
post_-attachment
table: post_-attachment
附表:
In the example above, it tells the post
(ID: 1) has 3 attachments
which is ID: 1,2 and 3. 在上面的例子中,它告诉
post
(ID:1)有3个attachments
,ID为1,2和3。
So, the question is How to GET the list of posts which will have columns posts.title
, attachments.filename
, attachments.file_url
in A SINGLE QUERY ? 那么,问题是如何获取将在单个查询中包含
posts.title
, attachments.filename
, attachments.file_url
列的帖子列表?
You must join the 3 tables: 您必须加入3个表:
select
p.*, a.*
from post p
left join post_attachment pa on pa.post_id = p.id
left join attachments a on a.id = pa.file_id
The LEFT JOIN
is needed in case a post does not have any attachments. 如果帖子没有任何附件,则需要
LEFT JOIN
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.