如何获得历史记录的最后一行

时间:2018-07-19 17:40:44

标签: mysql sql mariadb

我有这个查询:

SELECT id,
    numero_processo,
    assunto,
    (
        SELECT processo_historico.urgencia
        FROM processo_historico
        WHERE processo_historico.id_processo = processo.id
        ORDER BY processo_historico.id DESC LIMIT 1
     ) as urgencia,
     (
        SELECT processo_historico.nome_resp
        FROM processo_historico
        WHERE processo_historico.id_processo = processo.id
        ORDER BY processo_historico.id DESC LIMIT 1
     ) as nome_resp,
     (
        SELECT processo_historico.user_responsavel
        FROM processo_historico
        WHERE processo_historico.id_processo = processo.id 
        ORDER BY processo_historico.id DESC LIMIT 1
     ) as user_responsavel,
     (
         SELECT processo_historico.data_chegada
        FROM processo_historico
        WHERE processo_historico.id_processo = processo.id
        ORDER BY processo_historico.id DESC LIMIT 1
     ) as data_chegada,
     (
         SELECT processo_historico.distribuicao
        FROM processo_historico
        WHERE processo_historico.id_processo = processo.id
        ORDER BY processo_historico.id DESC LIMIT 1
      ) as distribuicao,
      (
          SELECT processo_historico.despacho
        FROM processo_historico
        WHERE processo_historico.id_processo = processo.id
        ORDER BY processo_historico.id DESC LIMIT 1
      ) as despacho,
      (
          SELECT processo_historico.parecer
        FROM processo_historico
        WHERE processo_historico.id_processo = processo.id
        ORDER BY processo_historico.id DESC LIMIT 1
      ) as parecer    

     FROM processo

正如你们所看到的,太多的子查询无法使每个'processo'包含最后一个插入的'processo_historico'行。

我该如何改善?还有一个问题,我该怎么放置这样的位置:

WHERE processo_historico.user_responsavel = *userinput*

这需要给我最后一个'processo_historico',而'user_responsavel'是一些数字。

表之间的关系是:“ processo” 1 x N“ processo_historico”

1 个答案:

答案 0 :(得分:0)

减少多个子查询以将每一列提取为一。

SELECT id,
processo.numero_processo,
processo.assunto,
ph.urgencia, 
ph.nome_resp,
ph.user_responsavel,
ph.data_chegada,
ph.distribuicao,
ph.despacho,
ph.parecer     
FROM processo
LEFT OUTER JOIN (    
    select
    processo_historico.urgencia, 
    processo_historico.nome_resp
    ,processo_historico.user_responsavel
    ,processo_historico.data_chegada
    ,processo_historico.distribuicao
    ,processo_historico.despacho
    ,processo_historico.parecer  
    FROM     
    processo_historico 
    WHERE ph.user_responsavel = *userinput*
    ORDER BY processo_historico.id DESC LIMIT 1)
AS ph ON ph.id_processo = processo.id