Tricky SQL for a simple function
November 23, 2007 1:38 AM
Subscribe
Been banging my head against the wall on this the whole day. I need a way to select & sort data from a single MySQL table, but it's a little bit more complicated that it seems.
Assume a table called "activity" with 4 fields - activity_id, activity_description, activity_datetime and project_id, which is a foreign key to the "project" table. This "activity" table stores all activity updates related to a project.
The "project" table is just project_id and project_name.
In a single SQL, I want to display a table that shows each project, ordered by its latest activity_datetime, like this:
Project X | "Client meeting" | 2007-11-23
Project Z | "Web design" | 2007-10-22
Project A | "Programming" | 2007-10-10
My current SQL does not work because MAX(activity_datetime) gives me the most recent activity, but activity_description still shows the first matching record.
SELECT *, MAX(activity_datetime) FROM activity a, project p WHERE a.project_id = p.project_id GROUP BY p.project_id
posted by arrowhead to computers & internet (14 comments total)
SELECT * FROM activity a, project p WHERE a.project_id = p.project_id GROUP BY p.project_id ORDER BY activity_datetime desc;
posted by evariste at 2:12 AM on November 23, 2007