Pergunta

Eu não sou pós -sexledev, tenho problemas em devolver apenas um valor na subconsulta.

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)

Retornará o conjunto vazio.

Quando eu derrubo o 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)

Retornará tudo da Tabela.

Estou tentando ter apenas o último valor da tabela

@Edit deve funcionar para cada m_id em tablea

Então, minha saída: m_id | Max (date_created) para esse m_id | ...

Foi útil?

Solução

Aqui está o SQL Fiddle que demonstra a seguinte 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
  )

Se suas mesas tiverem muitos registros, você poderá aplicar um intervalo em uma cláusula onde acelerar a consulta, assim:

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

Outras dicas

Mude a segunda consulta para:

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 em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top