如何订购LEFT的结果JOIN

问题描述 投票:1回答:2

我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"

按日期/时间排序

mysql sql
2个回答
0
投票

第一关

首先,你有你的加入条件的错误。

因此,每个岗位和每个评论有一个唯一的主键。这意味着你不能与commentId加入,因为帖子ID后可以有很多的意见..和每个评论需要不同的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


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一起发布的评论。

© www.soinside.com 2019 - 2024. All rights reserved.