我有一个代表一个简单演示论坛的postgres数据库。有两个表
主题
id | topic_id (the parent topic) | name | description
-------------------------------------------------------
uuid | uuid | text | text
和线程
id | topic_id | name | created_at
-------------------------------------------------------
uuid | uuid | text | timestamp without timezone
通过使用Express REST API,我想获取一个主题的所有信息。我传递了它的ID,并希望得到这样的结果
{
parentTopic: {}, // could be null if no parent is available
name: "",
description: "",
childTopics: [{}, {}, {}],
threads: [{}, {}, {}] // should be sorted by created_at
}
据我所知,不可能返回这样的结果。但是我试图创建一个查询来获取这些信息,也许以后我可以用一些代码来映射它。
SELECT
currentTopic.name,
currentTopic.description,
parentTopic.id AS parentTopicId,
parentTopic.name AS parentTopicName,
parentTopic.description AS parentTopicDescription,
childTopic.id AS childTopicId,
childTopic.name AS childTopicName,
childTopic.description AS childTopicDescription,
linkedThread.id AS threadId,
linkedThread.name AS threadName,
linkedThread.created_at AS threadCreatedAt
FROM
topic currentTopic
INNER JOIN
topic parentTopic ON currentTopic.topic_id = parentTopic.id
INNER JOIN
topic childTopic ON currentTopic.id = childTopic.topic_id
INNER JOIN
thread linkedThread ON currentTopic.id = linkedThread.topic_id
WHERE
currentTopic.id = '624aaab6-2d2d-45dc-a425-c2863f05779c'
ORDER BY
linkedThread.created_at;
执行此操作(我使用pgAdmin)时,没有错误发生,但返回0行。我确保应该检索一些条目。
该查询有问题吗?有没有一种方法可以改进查询以返回可以立即使用的结果(上面提到的JS对象)?
编辑:
以下是有关主题和主题的一些测试数据
主题表:
线程表:
答案 0 :(得分:1)
将内部联接更改为左联接
SELECT
currentTopic.name,
currentTopic.description,
parentTopic.id AS parentTopicId,
parentTopic.name AS parentTopicName,
parentTopic.description AS parentTopicDescription,
childTopic.id AS childTopicId,
childTopic.name AS childTopicName,
childTopic.description AS childTopicDescription,
linkedThread.id AS threadId,
linkedThread.name AS threadName,
linkedThread.created_at AS threadCreatedAt
FROM
topic currentTopic
left JOIN
topic parentTopic ON currentTopic.topic_id = parentTopic.id
left JOIN
topic childTopic ON currentTopic.id = childTopic.topic_id
left JOIN
thread linkedThread ON currentTopic.id = linkedThread.topic_id
WHERE
currentTopic.id = '624aaab6-2d2d-45dc-a425-c2863f05779c'
ORDER BY
linkedThread.created_at;