【问题标题】:Mysql - Single Query for One-To-ManyMysql - 一对多的单一查询
【发布时间】:2019-05-05 13:16:13
【问题描述】:

我有一个名为 posts 的表和另一个名为 attachments 的表...

一个post 可以有多个attachments...

所以,我创建了一个名为post_attachment..的中间表。

如何在A SINGLE QUERY中获取包含attachments数据的posts数据列表?

..

请参考以下内容,以便更清楚地理解...


表结构如下:

-

posts 表有 4 列:

  1. 身份证
  2. 标题
  3. body_text

-

attachments 表有 3 列:

  1. 身份证
  2. 文件名
  3. file_url

-

post_attachment 表有 2 列:

  1. post_id
  2. file_id

以下是具有多个attachmentspost 示例

posts表:

-

attachments表:

-

post_-attachment表:

在上面的示例中,它告诉post(ID:1)有 3 个attachments,即 ID:1,2 和 3。

所以,问题是如何获取在单一查询中包含posts.titleattachments.filenameattachments.file_url 列的帖子列表?

【问题讨论】:

    标签: mysql one-to-many


    【解决方案1】:

    您必须加入 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
    

    如果帖子没有任何附件,则需要LEFT JOIN

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多