Code: Select all
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");
Code: Select all
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
id
title
pFirst
Plast < /th>
postcount < /th>
< /tr>
< /thead>
7 < /td>
Dies ist ein Test < /td>
2025-01 16:00: 00: 00: 00: 00: 00: /> 2025-03-01 19:23:00 < /td>
3 < /td>
< /tr>
5 < /td>
Ein weiteres Thread < /td>
< /td> < /td>
/> null < /td>
< /tr>
6 < /td>
Einige Foxy -Sachen < /td>
null < /td> < /> < /td> < /td> < /> < /> < /td> < /td> < /> < /td> < /td> < /> < /td> < /td> < /> < /> />
Result I'd like to get:
id
title
pFirst
uFirst
pLast
uLast
postCount
7
Dies ist ein Test < /td>
2025-03-01 16:30:00 < /td>
1 < /td>
2025-03-01 19:23:00 < /td> < /> />
5
Another thread
null
null
null
6
Some foxy stuff
null
null
null