2010-12-14 145 views
0

說我有以下設置SQL查詢中返回從一個表彙總結果列

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

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

一些模擬數據

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 

我想回到回從職位表中的標題以及通過評論表中的ID與其相關的所有評論。

有點像。

Title   Comment 
Hello World  comment1 
Good Bye  comment2 
       comment3 
Pepsi   null 

這可能只是使用SQL?

回答

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 

但是題目會重複,即結果將是:

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

SELECT posts.title,comments.comment 來自帖子JOIN批語posts.id = comments.postid