2010-12-14 9 views
0

Say ISQL als eine Spalte aggregierte Ergebnisse aus einer Tabelle der Rückkehr in einer Abfrage

---Posts--- 
|id 
|Title 
----------- 

---Comments--- 
|id 
|postid 
|comment 
----------- 

Einige Mock Daten folgendes Setup

Posts 
ID  Title 
1   Hello World 
2   Good Bye 
3   Pepsi 

Comments 
ID  postid  comment 
1  1   comment 1 
2  2   comment 2 
3  2   comment 3 

Ich will den Titel der Beiträge Tisch zurückzukehren zurück und alle damit verbundenen Kommentare über die ID in der Kommentartabelle.

So etwas wie.

Title   Comment 
Hello World  comment1 
Good Bye  comment2 
       comment3 
Pepsi   null 

Ist dies nur mit SQL möglich?

Antwort

1
Select Title, 
     (SELECT GROUP_CONCAT(Comment) FROM Comments 
     WHERE 
     Comments.postid=posts.posts) as comments 
FROM posts 
0
Select Title, Comment 
from Posts p LEFT Join Comments c on c.PostId = p.id 
Order by 1 

Jedoch wird Titel wiederholt werden, wird also Ergebnis sein:

Title   Comment 
------------------------ 
Hello World  comment1 
Good Bye  comment2 
Good Bye  comment3 
Pepsi   null 
0

SELECT posts.title, comments.comment VON Beiträge Kommentare zu posts.id = comments.postid

JOIN
Verwandte Themen