Holen Sie sich Spalten, die mit aggregierten Ergebnissen mit mehreren Tabellen verbunden sindMySql

MySQL DBMS-Forum
Anonymous
 Holen Sie sich Spalten, die mit aggregierten Ergebnissen mit mehreren Tabellen verbunden sind

Post by Anonymous »

Die Web -Forum -Struktur hier. Meine aktuelle Abfrage erhält die Zeitstempel von den ältesten und neuesten Beiträgen, die jedem Thread zugeordnet sind. Was ich anscheinend nicht herausfinden kann, ist, wie die BenutzerID diesen Beiträgen zugeordnet werden kann. Ich habe hier ähnliche Fragen durchlesen, aber sie hatten einfachere Strukturen, bei denen alle aggregierten Daten in eine einzelne Spalte gruppiert werden konnten. Muss ich die Min, Max und in 3 separate Unterabfragen zählen? Ich habe versucht, die Gruppenklausel hinzuzufügen, die die Daten für jeden Benutzer, der einen Beitrag in den Threads besitzt, nur dupliziert. Ich bin ratlos, in welche Richtung ich von hier aus gehen soll.

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");
Abfrage:

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
Current Result:



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

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post