atokatim;10990387 wrote:The code above is still doing the same thing
There are only three things I can think of that might break his query. The first is that he lacks ft.title in the group by clause. If MySQL is not in strict mode, such queries will execute, but you cannot rely on them retrieving the proper data. It is possible that this query actually will retrieve the data you are looking for, since ft.id is in the group by clause and there is a one-to-one relationship between ft.id and ft.title. But I wouldn't count on it, and there's no reason for not following the standard which states that in a query with a group by clause, every selected field must be part of the group by clause or an aggregate function (MAX() is an aggregate function).
The second reason would be if you've mixed differenet types of ids when joinining tables. For example, your threads have id and tid (topic id), while your posts have tid (thread id), yet you happily join topic id and thread id since they happen to have the same names...
The third reason would be if you have added columns which aren't part of the group by clause or an aggregate function (such as including substr(post.message) among the selected fields.
CREATE TABLE thread (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(30),
sticky BOOL,
created DATETIME
);
CREATE TABLE post (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
thread_id INT UNSIGNED,
title VARCHAR(10),
created DATETIME,
FOREIGN KEY (thread_id) REFERENCES thread(id)
);
INSERT INTO thread (title, sticky, created) VALUES
('First', 0, '2011-10-01 14:00'),
('Second (sticky)', true, '2011-10-03 14:00'),
('Third (last posted to)', 0, '2011-10-10 14:00');
INSERT INTO post (thread_id, title, created) VALUES
(1, '(1) Oldest post', '2011-10-01 14:00'),
(1, '(1) Last post in thread', '2011-10-02 14:00'),
(2, '(2) First post', '2011-10-03 14:00'),
(2, '(2) Last post in thread', '2011-10-10 15:00'),
(3, '(3) First post', '2011-10-10 14:00'),
(3, '(3) Last post', '2011-10-11 16:00');
SELECT t.title, t.created, t.sticky, MAX(p.created)
FROM thread t
INNER JOIN post p ON p.thread_id = t.id
GROUP BY t.title, t.created, t.sticky
ORDER BY t.sticky DESC, p.created DESC;
output
[b]Thread title Sticky Thread created Last post created[/b]
Second (sticky) 1 2011-10-03 14:00:00 2011-10-10 15:00:00
Third (last posted to) 2011-10-10 14:00:00 2011-10-11 16:00:00
First 2011-10-01 14:00:00 2011-10-02 14:00:00
If you try adding post.title to the selected fields, you don't get data that makes any sense (MySQL non-strict mode), or the query won't execute at all (strict mode or other DBMS).
I had no topic id in my example, but the principles remain the same.