Get the top row of a group by date in a SQL join

I have 3 tables and I need to get the most recent row of the middle table in a join.

Table1 - Categories
ID - PK
Name - Varchar

Table2 - CatAction
ID - PK
CID - Int FK to ID in Categories
AID - Int FK to ID in Actions
last_run - date/time

Table 3 - Actions
ID - PK
Name - Varchar

When an "action" fires it updates the last_run field in CatAction by cid with the time it ran. I need to select all fields but only the last_run action by category. This is NOT what I want, but it shows the relationships of the tables

select * from categories c
LEFT JOIN cataction ca ON c.id=ca.cid
LEFT JOIN action a ON ca.aid=c.id

I also need a query that will count the number of actions by type by last run time. So I will need to group by action id as well.
skioneAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ralmadaCommented:
something like this for the first part.
select * from categories c
LEFT JOIN (
	select * from cataction t1
	where last_run = (select max(last_run) from cataction where cid = t1.cid)
) ca ON c.id=ca.cid
LEFT JOIN action a ON ca.aid=c.id

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ralmadaCommented:
and like this for the second part
select a.id, count(*) from categories c
LEFT JOIN (
	select * from cataction t1
	where last_run = (select max(last_run) from cataction where cid = t1.cid)
) ca ON c.id=ca.cid
LEFT JOIN action a ON ca.aid=c.id
group by a.id

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
MySQL Server

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.