Skip to content
Advertisement

Get last record from joined table

I have two tables DOCUMENT and SIGNATURES, like below

DOCUMENTS
doc_id    doc_name
1         Contract
2         Lead
3         Invoice 1
4         Invoice 2
5         Payment 123

SIGNATURES
sig_id    sig_doc_id     signature_name
1         1              Paul
2         2              Mark
3         1              Chew
4         2              Paul
5         3              John
6         3              Derek
7         3              Silvan
8         5              Roden

And I’m try to get last signature name.

EXPECTED OUTPUT
doc_id      doc_name      signature_name
1           Contract      Chew
2           Lead          Paul
3           Invoice 1     Silvan
4           Invoice 2             < empty because we not have signature
5           Payment 123   Roden

I have a SQL FIDDLE with database and query, but when run search no record has found.

http://sqlfiddle.com/#!9/b98474/3

Here my query

SELECT docs.*, sign.*
FROM cnt_man_docs docs
INNER JOIN cnt_man_doc_signatures sign ON docs.cnt_man_doc_id = sign.cnt_man_doc_signature_doc_id
WHERE sign.cnt_man_doc_signature_id = 
(SELECT MAX(cnt_man_doc_signature_id)
FROM cnt_man_doc_signatures
WHERE sign.cnt_man_doc_signature_id = docs.cnt_man_doc_id)

Advertisement

Answer

A simple method is a correlated subquery:

select d.*,
       (select s.signature_name
        from signatures s
        where s.sig_doc_id = d.doc_id
        order by s.sig_id desc
        limit 1
       ) as signature_name
from documents d;

With an index on signatures(doc_id, sig_id desc, signature_name) this is probably the fastest method as well.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement