Domanda

Non sono Postgredev, ho avuto problemi con il restituzione di un solo valore nella sottoquery.

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)

Restituirà un set vuoto.

Quando prendo il limite 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)

Restituirà tutto da TableB.

Sto cercando di avere solo l'ultimo valore dalla tabellab

@Edit dovrebbe funzionare per ogni m_id in tablea

Quindi il mio output: m_id | Max (date_created) per quel m_id | ...

È stato utile?

Soluzione

Ecco il Violino SQL Ciò dimostra la seguente domanda:

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
  )

Se le tue tabelle hanno molti record, potresti voler applicare un intervallo in una clausola dove accelerare la query, in questo modo:

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

Altri suggerimenti

Cambia la seconda domanda in:

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)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top