2013-07-07 19 views
0

我有以下表格:排序和按日期連接兩個表

posts 
post_id | text | posts_date 
1  | blabla | 06-06-2013 
2  | bababa | 09-06-2013 
... 

comments 
comment_id | post_id | user_id | text   | comments_date 
1   | 1  | 55  | I like this... | 06-08-2013 
2   | 1  | 66  | Yeah, me also! | 06-07-2013 
3   | 2  | 55  | I like this... | 06-10-2013 
4   | 2  | 66  | Yeah, me also! | 06-11-2013 
... 

我需要返回從表和訂單他們先通過posts_date和所有列的SQL語句然後通過評論日期這篇文章。

所以從查詢結果表應該是

post_id | text | posts_date | comment_id | user_id | text   | comments_date 
1  | blabla | 06-06-2013 | 2   | 66  | Yeah, me also! | 06-07-2013 
1  | blabla | 06-06-2013 | 1   | 55  | I like this... | 06-08-2013 
2  | bababa | 09-06-2013 | 3   | 55  | I like this... | 06-10-2013 
2  | bababa | 09-06-2013 | 4   | 66  | Yeah, me also! | 06-11-2013 

我想到了什麼樣

SELECT * FROM comments c, (SELECT * FROM posts ORDER BY posts_date ASC) p WHERE p.post_id = c.post_id ORDER BY comments_date ASC 

,但似乎並沒有給出正確的結果。

回答

1
SELECT * 
FROM COMMENTS C JOIN POSTS P ON C.post_id = P.post_id 
ORDER BY P.posts_date,C.comments_date ASC 
1
Select * From Posts 
inner join Comments on Posts.Post_id = Comments.Post_ID 
order by posts.Post_date, comments.comment_date 

會給你只能用評論的帖子。

如果你想要的職位,即使他們沒有任何評論,那麼

Select * From Posts 
left join Comments on Posts.Post_id = Comments.Post_ID 
order by posts.Post_date, comments.comment_date 

瞭解加入的隊友,沒有他們不能離開家。