gpt4 book ai didi

javascript - select 返回零行,尽管它应该返回一些条目

转载 作者:行者123 更新时间:2023-12-03 00:00:18 24 4
gpt4 key购买 nike

我有一个 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 对象)?

编辑:

这是线程和主题的一些测试数据

主题表:

enter image description here

线程表:

enter image description here

最佳答案

将内连接更改为左连接

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;

关于javascript - select 返回零行,尽管它应该返回一些条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55205134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com