数据库left join 机制:数据库-leftjoin与多个order
数据库left join 机制:数据库-leftjoin与多个order我是@爱玩的安哥,关注我获取更多有用知识ORDER BY practices.created_at desc comments.created_at DESC 结果会是这样的:https://cn.bing.com/search?q=left join inner join 区别因为有评论的要在前,所以comment.created_at要写在前面,表示这个是主排序,ORDER BY comments.created_at DESC practices.created_at desc如果practices.created_at在前面,
有这个么需求,一些练习会有人评论,在列出练习时要将有评论的练习排在前面,这时候可以使用left join与多个order by的办法来达到要求。
首先,有practice_id为3539、3715、3514三个练习是有人评论的,3514评论时间为最新:
SELECT
    * 
FROM
    comments 
WHERE
    practice_id IN ( 3514  3715  3527  3539 )
    

SELECT
    `practices`.* 
FROM
    `practices`
    left JOIN `comments` ON `comments`.`practice_id` = `practices`.`id` 
WHERE
    `practices`.`user_id` = 7 
    AND `practices`.`pth_sentence_id` = 755 
    AND `practices`.`del` = FALSE 
    
解读下:
- WHERE条件: 找到user_id为7的用户,而且其练习的句子id为755,并且del为false(使用了软删除的办法,只标记,并不真的删除)
 - FROM中,practices是练习表,使用左连接,这样可以显示满足条件的所有练习记录(不管有没有评论)。
 

如果你使用inner join,只能得到完全满足inner join中条件的记录,共三条,与第一张图对应上了

https://cn.bing.com/search?q=left join inner join 区别
多个order by因为有评论的要在前,所以comment.created_at要写在前面,表示这个是主排序,
ORDER BY
    comments.created_at DESC 
    practices.created_at desc
    

如果practices.created_at在前面,
ORDER BY
    practices.created_at desc 
    comments.created_at DESC
    
    
结果会是这样的:

我是@爱玩的安哥,关注我获取更多有用知识




