The query is coming up empty even though there are expected results

My project involves a Postgres database that serves as a demo forum. Within this database, there are two tables:

topic

id   | topic_id (the parent topic) | name | description
-------------------------------------------------------
uuid | uuid                        | text | text

and thread

id   | topic_id | name | created_at
-------------------------------------------------------
uuid | uuid     | text | timestamp without timezone

I am exploring options to retrieve all the information for a specific topic using an Express REST API. I would like the result to be structured like this:

{
    parentTopic: {}, // could be null if no parent is available
    name: "",
    description: "",
    childTopics: [{}, {}, {}],
    threads: [{}, {}, {}] // should be sorted by created_at
}

I understand that returning a result in this exact format may not be straightforward. However, I have attempted to create a query that can extract this information, which I plan to further process with code later on.

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;

While executing this query (using pgAdmin), I encountered no errors, but it returned 0 rows. I have verified that there are entries available to retrieve.

Could there be an issue with the query? Is there room for improvement to ensure the query returns a usable result structure (similar to the JS object mentioned earlier)?

Edit:

Below is some sample data from both the threads and topics tables:

Topic table:

https://i.sstatic.net/bv4Bo.png

Thread table:

https://i.sstatic.net/0ulC8.png

Answer №1

Modify the SQL query by changing inner join to left join

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;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unlimited scrolling feature resembling Facebook and Tumblr created using jQuery

Below is the modified code from a tutorial found on hycus.com: <script type="text/javascript> var properlast = 10; $(window).scroll(function() { if($(window).scrollTop() == $(document).height() - $(window).height()) { $("div#load ...

Guide to sending a socket.io response in a post request using NodeJS

I've got a node server up and running with a React application that's integrated with Socket.io, and everything is working smoothly. However, I also have an external application that relies on the same data. My goal is to post to my node server w ...

Endless Scroll Feature in Javascript

A brief tale: I am in search of a way to extract data from a website that features infinite scroll without actually implementing the infinite scroll feature myself. My plan is to create a script that will auto-scroll the page from the browser console, wai ...

Trouble expanding Bootstrap Dropdown menu on mobile devices

I am currently facing an issue with a Bootstrap navbar that includes a dropdown menu for selecting courses. On my desktop, everything works perfectly fine when I click on the courses tab. However, when I try to select a course on mobile, nothing happens. ...

What is the most efficient method for identifying and modifying an element's in-line style while performing a swipe gesture?

Recently, I've been developing a left swipe gesture handler for chat bubbles. Implementing touchMove and touchStart seems like the logical next step, but for now, I'm focusing on making it work seamlessly for PC/web users. I managed to make it f ...

How can I retrieve the name of a React component in the most effective way?

My current challenge is figuring out how to retrieve the name of a React component. I initially attempted using the this.constructor.name property, but discovered that it doesn't function properly in production mode due to code minification by Webpack ...

Tips for creating text that adjusts to different screen sizes within a div

I am trying to ensure that the height on the left side matches the height on the right, so it's important that it looks good on various devices like tablets, PCs, etc. However, when I resize my browser window, the video on the right side shrinks while ...

The challenge of handling success and error messages in Ajax with HTML

I encountered an issue with this concrete problem. My goal is to dynamically display a message within a specific div based on the response from my ajax request. I have set up two divs with IDs #uploadResponsesuccess and #uploadResponseerror. However, since ...

The React Component in Next.js does not come equipped with CSS Module functionality

I have been attempting to incorporate and apply CSS styles from a module to a React component, but the styles are not being applied, and the CSS is not being included at all. Here is the current code snippet: ./components/Toolbar.tsx import styles from & ...

How can I incorporate a JavaScript module into my Typescript code when importing from Typeings?

Exploring Angular2 and Typescript with the help of mgechev's angular2-seed for a new project has been an interesting experience. However, I have encountered a problem along the way. My intention is to incorporate Numeral into a component, and here ar ...

Execute a task in jQuery once the toggle() function has finished

I have a scroll functionality, and I want to perform an action after the toggle event is completed. The problem I'm facing is that my function gets triggered multiple times because it runs on every scroll. Pseudo flow: // Hide div if visible on scro ...

Creating obstacles in a canvas can add an extra layer of challenges and

I am working on creating a basic platformer game using the code displayed below. window.onload = function(){ var canvas = document.getElementById('game'); var ctx = canvas.getContext("2d"); var rightKeyPress = false; var leftKeyPress = false; ...

Best method for developing a jQuery plugin

I've been working on developing my own jquery module, but I want to make sure I'm heading in the right direction before things get too complicated. Although it's not shown in this demo, the main goal is to retrieve content via ajax, so the ...

Possible Rewrite: "Is it possible to dynamically adjust the `<p>` value when modifying the range meter in JavaScript?"

I'm looking to replicate this functionality, but in the current code, I have a separate function for each DIV. Is there another way to achieve the same outcome with fewer functions? As it stands, adding multiple options would require writing multiple ...

Extract a parameter value from a URL included in a GET request. Error message: "Property cannot be read due to TypeError."

Trying to extract data from the URL route parameters in a GET request has become quite a challenge. It seemed to work perfectly fine before, without any changes. Now, nothing seems to be working as expected. I have scattered console.log statements all ove ...

When I tried to use the zoom-in feature in Cropper.js, I encountered some issues with the centered cropped image

I am encountering an issue with Cropper.js. My goal is to zoom in on the image while cropping, ensuring that the crop box remains centered as I drag and modify it. Additionally, after cropping a piece of the image, that cropped portion should also be cente ...

Step-by-step guide on clipping a path from an image and adjusting the brightness of the remaining unclipped area

Struggling to use clip-path to create a QR code scanner effect on an image. I've tried multiple approaches but can't seem to get it right. Here's what I'm aiming for: https://i.stack.imgur.com/UFcLQ.png I want to clip a square shape f ...

Exploring the magic of jQuery validation alongside the versatility of Twitter Bootstrap panels

Seeking assistance with a bootstrap (ecommerce checkout) form that utilizes the jquery validation plugin. I am trying to achieve specific behaviors: Currently, when the panel collapses, the validation event should trigger according to the code provided; ...

Mastering the art of utilizing Context API and Provider for optimal functionality

Currently, I am working on implementing a dark mode feature in my project. Despite everything appearing to be set up correctly, it seems like the Context at App is not re-rendering when I use the setTheme function inside the Provider. Can someone help me t ...

JS implement a secure retrieve function without relying on strings

When working with Lodash, one common function utilized is get, which allows for retrieval of nested properties in objects like this: _.get(object, 'a[0].b.c'); // => 3 _.get(object, ['a', '0', 'b', 'c' ...