I want to join these two tables, showing the most recent due date for every client:
Table "clients":
| id_client | name |
|-----------|------------|
| 1 | Customer 1 |
| 2 | Customer 2 |
| 3 | Customer 3 |
Table "invoices" (FK id_client):
| id_invoice | id_client | due_date | payment_frequency |
|------------|-----------|------------|-------------------|
| 1 | 1 | 2018-11-30 | monthly |
| 2 | 1 | 2018-12-30 | monthly |
| 3 | 2 | 2019-01-01 | quarterly |
| 4 | 2 | 2019-01-01 | quarterly |
Desired result:
| id_client | name | due_date | payment_frequency |
|-----------|------------|------------|-------------------|
| 1 | Customer 1 | 2018-12-30 | monthly |
| 2 | Customer 2 | 2019-01-01 | quarterly |
| 3 | Customer 3 | (null) | (null) |
Details:
It should return all clients records, even those with no invoices (null).
Some customers have more than one invoice that due on the same date (id_invoice 3 and 4 in this example), but only one record should be returned.
I was able to make it work through the following query:
SELECT
c.id_client,c.name,
(SELECT due_date FROM invoices WHERE id_client=c.id_client ORDER BY due_date DESC LIMIT 1) AS due_date,
(SELECT payment_frequency FROM invoices WHERE id_client=c.id_client ORDER BY due_date DESC LIMIT 1) AS payment_frequency
FROM
clients AS c
I think there are more elegant and better-performing ways, through joins. Can you give me your suggestion please?
This table structure, data and query at Fiddle Ps. Despite the question is marked as a duplicate, other questions and answers do not solve this case.