Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining 2 select queries on 2 different tables in PostgreSQL

Tags:

sql

postgresql

I have two separate queries on 2 different tables which I am trying to join into one query. Both tables are within the same schema.

I am trying to form a query which will return the forumid, threadid and subject of the most recent post in a forum. I can use the two queries I wrote below, but for the sake of efficiency I would prefer to use just one if possible.

The following are my queries:

1>
SELECT forumid,threadid
FROM threadtable
WHERE modifieddate = (select max(modifieddate) from threadtable);

2>
SELECT subject
FROM messsagetable
WHERE modifieddate = (select max(modifieddate) from messsagetable);

I have tried a few solutions but seem to be going round in circles. Any suggestions appreciated. Version is Postgres 8.1.

like image 975
James Avatar asked May 20 '13 16:05

James


People also ask

How do I join two SELECT queries in PostgreSQL?

The UNION operator combines result sets of two or more SELECT statements into a single result set. To combine the result sets of two queries using the UNION operator, the queries must conform to the following rules: The number and the order of the columns in the select list of both queries must be the same.

What is the most efficient way of joining 2 table in same database?

Relational algebra is the most common way of writing a query and also the most natural way to do so. The code is clean, easy to troubleshoot, and unsurprisingly, it is also the most efficient way to join two tables.


1 Answers

To combine the results unconditionally use a CROSS JOIN:

SELECT *
FROM  (
    SELECT forumid, threadid
    FROM   threadtable
    ORDER  BY modifieddate DESC
    LIMIT  1
    ) t
CROSS JOIN (
    SELECT subject
    FROM   messsagetable
    ORDER  BY modifieddate DESC
    LIMIT  1
    ) m;

I modified the base queries with the faster and simpler ORDER BY / LIMIT 1. If there are multiple rows in either table sharing the maximum modifieddate, an arbitrary one will be picked.
You could add more items to the ORDER BY clause to pick a certain row in such a case.

Update after comment

however the modifieddate field is in both tables and in the case of the entries I am trying to retrieve it will be the same.

That's a broken design. You need a current version of Postgres and you need to reconsider your database layout.
As for now, the above query still does the job as requested - once you got your table names straight.

like image 61
Erwin Brandstetter Avatar answered Oct 17 '22 05:10

Erwin Brandstetter