【问题标题】:Sort and Join two tables by date按日期对两个表进行排序和连接
【发布时间】:2013-07-07 14:52:44
【问题描述】:

我有以下表格:

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
...

我需要一个 sql 语句,它返回两个表中的所有列,并首先按 posts_date 排序,然后按 cmets_date 排序。

所以查询的结果表应该是

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

但这似乎没有给出正确的结果。

【问题讨论】:

    标签: mysql sorting sql-order-by


    【解决方案1】:
    SELECT * 
    FROM COMMENTS C JOIN POSTS P ON C.post_id = P.post_id 
    ORDER BY P.posts_date,C.comments_date ASC
    

    【讨论】:

      【解决方案2】:
      Select * From Posts
      inner join Comments on Posts.Post_id = Comments.Post_ID
      order by posts.Post_date, comments.comment_date
      

      只会给你带有 cmets 的帖子。

      如果你想要帖子,即使他们没有任何 cmets 然后

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

      Learn 加入 mate,没有他们就不能离开家。

      【讨论】:

        猜你喜欢
        • 2018-01-14
        • 1970-01-01
        • 2017-02-05
        • 2020-10-30
        • 1970-01-01
        • 1970-01-01
        • 2015-12-04
        • 1970-01-01
        相关资源
        最近更新 更多