Код: Выделить всё
CREATE TABLE post (id int NOT NULL AUTO_INCREMENT, postDate datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, userid int NOT NULL, threadId int NOT NULL, PRIMARY KEY(id));
INSERT INTO post (postDate, userid, threadId) VALUES("2025-3-1 16:30:00", 1, 7);
INSERT INTO post (postDate, userid, threadId) VALUES("2025-3-1 17:57:00", 2, 7);
INSERT INTO post (postDate, userid, threadId) VALUES("2025-3-1 19:23:00", 3, 7);
CREATE TABLE users (id int NOT NULL AUTO_INCREMENT, name varchar(50), PRIMARY KEY(id));
INSERT INTO users (id, name) VALUES(1, "Bob");
INSERT INTO users (id, name) VALUES(2, "Steve");
INSERT INTO users (id, name) VALUES(3, "Mary");
CREATE TABLE thread (id int NOT NULL AUTO_INCREMENT, title varchar(100), PRIMARY KEY(id));
INSERT INTO thread (id, title) VALUES(5, "Another thread");
INSERT INTO thread (id, title) VALUES(6, "Some foxy stuff");
INSERT INTO thread (id, title) VALUES(7, "This is a test");
SELECT t.id, t.title, x.pFirst, x.pLast, x.postCount, x.userid
FROM thread t
LEFT JOIN (
SELECT threadId, MIN(postDate) pFirst, MAX(postDate) pLast, count(p.id) as postCount
FROM post p
GROUP BY threadId
) x ON x.threadId = t.id
ORDER BY pLast DESC
< /code>
Текущий результат: < /strong>
| id | Название | Pfirst | пласт | postcount |
| -------------- | ------------------- | ----------------------- | ----------------------- | ----------- |
| 7 | Это тест | 2025-03-01 16:30:00 | 2025-03-01 19:23:00 | 3 |
| 5 | Другая нить | null | null | null |
| 6 | Некоторые лисицы | null | null | null | < /p>
Результат я бы хотел получить: < /strong>
| id | Название | Pfirst | Ufirst | пласт | уласт | postcount |
| -------------- | ------------------- | ----------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ----------- |
| 7 | Это тест | 2025-03-01 16:30:00 | 1 | 2025-03-01 19:23:00 | 3 | 3 |
| 5 | Другая нить | null | | null | | null |
| 6 | Некоторые лисицы | null | | null | | NULL |
Подробнее здесь: https://stackoverflow.com/questions/794 ... ple-tables