如何订购LEFT JOIN的结果

时间:2019-02-05 10:54:04

标签: mysql sql

我的LEFT JOIN查询工作正常,但在排序查询结果时遇到问题。

查询是

SELECT * 
FROM posts 
LEFT JOIN comments ON posts.postId = comments.commentId 
ORDER BY postDate DESC, commentDate DESC

相反,评论会在我列表的末尾拉出。

帖子

postId (Primary)    int(11)      AUTO_INCREMENT
postUserId          int(11)
postType            varchar(10)
postContent         text
postCaption         text
postState           varchar(10)
postVotes           int(11)
postDate            datetime

和评论

commentId (Primary) int(11)     AUTO_INCREMENT
commentUserId       int(11)
commentFor          varchar(20)
commentForId        int(11)
commentContent      text
commentState        varchar(20)
commentVotes        int(11)
commentDate         datetime

从查询中注释的顺序不正确 从数据库中提取原始数据 首先从评论中拉出

"1","1","post","1","this is one comment and the only one","published","1","2019-02-05 12:04:00"

这是来自帖子

"1","1","text","this is the first post",,"published","1","2019-02-05 12:02:00"
"2","1","text","this is the second post",,"published","1","2019-02-05 12:16:00"

所需结果应该像

"2","1","text","this is the second post",,"published","1","2019-02-05 12:16:00"
"1","1","post","1","this is one comment and the only one","published","1","2019-02-05 12:04:00"
"1","1","text","this is the first post",,"published","1","2019-02-05 12:02:00"

按日期/时间排序

2 个答案:

答案 0 :(得分:0)

先行

首先,您的加入条件有误。

因此,每个帖子和每个评论都有一个唯一的主键。 这意味着您无法将postId与commentId结合使用,因为一个帖子可以包含许多评论..并且每个评论都需要一个不同的ID。

所以正确的条件是:

SELECT * 
FROM posts 
LEFT JOIN comments ON posts.postId = comments.commentForId 
ORDER BY postDate DESC, commentDate DESC

具有嵌套查询和顺序的UNION

现在,要组合和排序评论和帖子的结果,您需要使用嵌套查询和UNION。

示例:

select * from

(select postId as entryId, postContent as content, postDate as timestamp from posts
UNION
select commentId, commentContent, commentDate from comments)temp

ORDER BY temp.timestamp DESC;

有数据:

create table posts(
  postId int,
  postContent text,
  postDate datetime
  );

  create table comments(
    commentId int,
    commentForId int,
    commentContent text,
    commentDate datetime);

    insert into posts values (1, 'this is the first post', "2019-02-05 12:02:00");
    insert into posts values (2, 'this is the second post', "2019-02-05 12:16:00");

    insert into comments values (1, 1, 'this is the comment', "2019-02-05 12:04:00");      

查看小提琴:https://www.db-fiddle.com/f/koRapukYqcSxWLNQ8hSA7Y/0

答案 1 :(得分:0)

您的JOIN条件可疑:

posts.postId = comments.commentId 

这表明名称完全不同的ID应该匹配。

大概是您打算的:

SELECT p.*, c.*   -- you should list the columns you want
FROM posts p LEFT JOIN
     comments c
     ON p.postId = c.postId 
ORDER BY p.postDate DESC, c.commentDate DESC;

我不是100%肯定会解决您的订购逻辑,但这至少应该返回更合理的结果集。就是说,我想按帖子和日期保持帖子的顺序,所以我将使用:

ORDER BY p.postDate DESC, p.postid, c.commentDate DESC;

这将使对具有相同postDate的帖子发表评论。