我试图从两个表中选择一些数据,但它比我最初想象的要复杂一些。我有两个表(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 |
+----+----------+----------+-----------+
表格的设置方式如下, 我在我的网站上创建了一篇“文章”,其中包含以下内容:
- 文章标题
- 文章正文
- 文章主类别
- 文章子类别
我需要从表内容
中获取每篇文章以及关联的主类别和子类别
例如,它会带回这一行 ->
另一个标题,另一个正文,类别 10,子类别 20
因为在关系表中,源 id 是 2,它链接到文章的 elementId,而 targetId 是与文章关联的类别的 ID。
实现这一目标的最佳方法是什么?我尝试了几种不同的查询来使其工作,但似乎不可能
最佳答案
我认为您的关系表数据存在错误,这可能是基于邻接表模型的:
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
关于MySQL 从关系表连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45504939/