Search code examples
sqlpostgresqlsubquerycorrelated-subquery

PostgreSQL Subquery join and one value


Im not PostgreDev, got problem with returning just one value in subquery.

select * from
(
select m_id from TableA where m_id = 236779

)Main
inner  join
(
select m_m_id as l_m_id,date_created as l_date_created
from TableB
where
proc_type <> '-'
order by date_created desc limit 1
) CheckLastCode on (Main.m_id = CheckLastCode.l_m_id)

Will return empty set.

When I take down limit 1

select * from
(
select m_id from TableA where m_id = 236779

)Main
inner  join
(
select m_m_id as l_m_id,date_created as l_date_created
from TableB
where
proc_type <> '-'
order by date_created desc
) CheckLastCode on (Main.m_id = CheckLastCode.l_m_id)

Will return all from TableB.

Im trying to have just last value from tableB

@EDIT It should work for every m_id in tableA

So my output: M_ID | MAX(DATE_CREATED) for that M_ID| ...


Solution

  • Here is the SQL Fiddle that demonstrates the following query:

    SELECT * 
    FROM TableA AS a
      JOIN TableB as b 
      ON a.m_id = b.m_m_id AND b.date_created = 
      (
        SELECT MAX(bs.date_created) 
        FROM TableB bs
        WHERE bs.m_m_id = a.m_id
        LIMIT 1
      )
    

    If your tables have a lot of records you may want to apply a range in a WHERE clause to speed up the query, like so:

    SELECT * 
    FROM TableA AS a
      JOIN TableB as b 
      ON a.m_id = b.m_m_id AND b.date_created = 
      (
        SELECT MAX(bs.date_created) 
        FROM TableB bs
        WHERE bs.m_m_id = a.m_id
        LIMIT 1
      )
    WHERE a.m_id BETWEEN 2 AND 3