I have two tables: companies and emails.
I would like to select the last email of every company
I tried this:
SELECT *
FROM companies
LEFT
JOIN emails
ON companies.company_id = emails.company_id
WHERE companies.status = 'active'
GROUP
BY emails.company_id
ORDER
BY emails.date DESC;
But this doesn't work, the ORDER BY part should somehow precede the GROUP BY part, because I want to get the last email of every company, not sort the end results.
Can someone help me?
Thanks.
UPDATE
I ended up doing this:
SELECT *
FROM companies
LEFT
JOIN (
SELECT company_id, date
FROM emails
ORDER
BY date DESC
) emails
ON companies.company_id = emails.company_id
WHERE companies.status = 'active'
GROUP
BY emails.company_id;
Thank you for the help.