MySQL从关系表加入

时间:2017-08-04 10:51:43

标签: mysql

我正在尝试从两个表中选择一些数据,但它比我想象的要复杂一些。我有两张桌子(content& relations)。

    content
    +----+-----------+--------------------+--------------+
    | id | elementId |       title        |  field_body  |
    +----+-----------+--------------------+--------------+
    |  1 |         1 | test title         | test body    |
    |  2 |         2 | another title      | another body |
    |  3 |         3 | category 10        | null         |
    |  4 |         4 | sub category 20    | null         |
    +----+-----------+--------------------+--------------+


    relations
    +----+----------+----------+-----------+
    | id | sourceId | targetId | sortOrder |
    +----+----------+----------+-----------+
    |  1 |        2 |        3 |         1 |
    |  2 |        2 |        4 |         2 |
    +----+----------+----------+-----------+

表的设置方式如下, 我在我的网站上创建了一篇“文章”,其中包含以下内容:

  • 文章标题
  • 文章正文
  • 文章主要类别
  • 文章子类别

我需要从表content

中获取每篇文章以及相关的主要和子类别

例如,它会带回这一行 - >

another title, another body, category10, sub category 20

因为在关系表中,源ID是2,它链接到文章的elementId,而targetId是要与文章关联的类别的ID。

这样做最好的方法是什么?我已经尝试了几种不同的查询来实现这一点,但似乎不可能

1 个答案:

答案 0 :(得分:0)

我认为你的关系表数据存在错误,这可能是基于邻接列表模型:

带有id == 2的

记录必须有sourceId字段== 3:

relations
    +----+----------+----------+-----------+
    | id | sourceId | targetId | sortOrder |
    +----+----------+----------+-----------+
    |  1 |        2 |        3 |         1 |
    |  2 |        3 |        4 |         2 |
    +----+----------+----------+-----------+

之后你可以试试这个sql:

select
c.id,
c.title as article_title,
c.field_body as article_body,
c1.title as article_main_category,
c2.title as article_sub_category
from
content c
join relations as r1 on r1.sourceId = c.elementId
join content as c1 on c1.elementId = r1.targetId
join relations as r2 on r2.sourceId = c1.elementId
join content as c2 on c2.elementId = r2.targetId

如果关系表数据没问题,并且sortOrder字段有意义,那么我们可以尝试这个SQL查询:

select
c.id,
c.title as article_title,
c.field_body as article_body,
c1.title as article_main_category,
c2.title as article_sub_category
from
content c
join relations as r1 on r1.sourceId = c.elementId and r1.sortOrder = 1
join content as c1 on c1.elementId = r1.targetId
join relations as r2 on r2.sourceId = c.elementId and r2.sortOrder = 2
join content as c2 on c2.elementId = r2.targetId