I need to select the last register for each budget_id, which is a foreign key.
For example, if my table is:
id | budget_id | comment
1 | 8 | Test 1
2 | 8 | Test 2
3 | 5 | Test 1
4 | 5 | Test 2
I need to retrieve like this:
id | budget_id | comment
4 | 5 | Test 2
2 | 8 | Test 2
But it is always showing the first register for each budget_id. Intead of Test 2, it shows Test 1.
Here is my SQL so far:
SELECT *
FROM note
GROUP BY budget_id
ORDER BY id DESC
I have tried adding HAVING, sub selects selecting the MAX field created_at, but nothing.
EDIT
After doing what I was told, I kind of managed to make it work, but now the query only returns the SECOND register of each budget_id. Here is my SQL:
SELECT MAX(n.id),
c.name,
MAX(n.comment)
FROM note n,
budget b,
customer c
WHERE n.budget_id = b.id
AND b.customer_id = c.id
GROUP BY n.budget_id
ORDER BY n.id DESC