Verwenden Sie ein auf dem blog_comments
Tisch selbstschließen. Diese Abfrage wird die 5 neuesten Blogposts zusammen mit allen ihren Kindern eines Nachkommen tief geben.
SELECT t1.id AS parentID, t2.id AS childID, t1.content AS parentContent,
t2.content AS childContent
FROM
(
SELECT id, content
FROM blog_comments
ORDER BY creation_date DESC
LIMIT 5
) t1
INNER JOIN blog_comments t2
ON t1.id = t2.parent
ORDER BY t1.id, t2.id
Update:
ich viel lieber bevorzugen die folgende Abfrage, die die fünf neuesten Blog-Posts zeigt, die jeweils auf einer eigenen Zeile, gefolgt von allen Kindern antwortet. Dies ähnelt mehr dem, was Sie in Ihrer App-Ebene anzeigen möchten.
SELECT
CASE WHEN t.childId = -1 THEN 'parent' ELSE 'child' END AS type,
t.content
FROM
(
SELECT childId, parentId, content FROM
(
SELECT -1 AS childId, id AS parentId, content AS content
FROM blog_comments
WHERE parent IS NULL
ORDER BY creation_date DESC
LIMIT 5
) t1
UNION ALL
SELECT t1.id AS childId, t1.parent AS parentId, t1.content AS content
FROM blog_comments t1
INNER JOIN
(
SELECT id
FROM blog_comments
WHERE parent IS NULL
ORDER BY creation_date DESC
LIMIT 5
) t2
ON t1.parent = t2.id
) t
ORDER BY t.parentId, t.childId
Hier ist ein Link zu einer laufenden Demo:
Der Tabellenname ** blog_comments ist **. –
Was hast du probiert? (Oh, und bearbeiten Sie Ihre Frage, anstatt Korrekturen als Kommentare, bitte) –
Vielen Dank für die Antwort. Ich habe versucht, SELECT ' FROM blog_comments JOIN blog_comments ON blog_comments.parent = blog_comments.id WHERE blog_comments.post_id = 1; 'und ich habe den Fehler' Fehler in Abfrage (1066): Nicht eindeutige Tabelle/Alias: 'blog_comments' '. –