Firstly, I am using the node-postgres
module to access database in a node application.
I have this SQL code that pulls up data from a table data of which is pulled from another table.
SELECT dwa_id
FROM _tasks2dwa
WHERE task_id IN
(
SELECT task_id
FROM _tasks
WHERE onetsoc_code IN
(
SELECT onetsoc_code
FROM _alternate_titles
WHERE alternate_title
ILIKE '%Beta Tester%'
)
)
I would like to use this query like client.query(query)
(Please refer to the docs).
I would like to use the intermediate result (the table that is comprised of values of task_id
) in a backend application. However I also need the end result, the table that is comprised of values of dwa_id
in that backend application. I have a solution which is writing a separate query for each result, which seems inefficient. Is there another more efficient approach to this problem?
Best Answer
You will need to store the intermediate result in a temporary table, but there is no way to avoid the two queries:
Then, using the same (physical) connection to the database, you can run the query to retrieve the intermediate result:
And the actual result you want:
If you only want (or get) each
dwa_id
only once, another option is to aggregate the task_ids into an array:Something along the lines: