简体   繁体   English

Mysql - 一对多的单一查询

[英]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列:

  1. id ID
  2. title 标题
  3. body_text 文章主体

- -

attachments table have 3 columns: attachments表有3列:

  1. id ID
  2. filename 文档名称
  3. file_url FILE_URL

- -

post_attachment table have 2 columns: post_attachment表有2列:

  1. post_id POST_ID
  2. file_id FILE_ID

Below are the example of a post that have multiple attachments 以下是具有多个attachmentspost的示例

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.titleattachments.filenameattachments.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM