Pregunta

No soy Postgredev, tengo un problema para devolver un solo valor en 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)

Devolverá el conjunto vacío.

Cuando tomo el límite 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)

Volverá todo de TableB.

Estoy tratando de tener el último valor de tableB

@Edit debería funcionar para cada m_id en cuadro

Entonces mi salida: m_id | Max (date_created) para eso m_id | ...

¿Fue útil?

Solución

Aquí está el Violín SQL Eso demuestra la siguiente consulta:

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
  )

Si sus tablas tienen muchos registros, es posible que desee aplicar un rango en una cláusula Where para acelerar la consulta, así:

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

Otros consejos

Cambie la segunda consulta a:

select m_m_id as l_m_id,date_created as l_date_created
  from TableB
 where proc_type <> '-'
   and date_created = (select max(date_created) 
                        from TableB 
                        where m_m_id = 236779 limit 1)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top