mysql 选最大的元素,如何在MySQL中选择每行的两个元素的最大值

该博客探讨如何在SQL中对包含帖子和评论创建时间的表进行排序,特别是当某些帖子没有评论时。解决方案涉及使用LEFT JOIN和RIGHT JOIN结合COALESCE函数,以获取每个帖子或其最新评论的最大创建时间,并按此时间降序排列。
摘要由CSDN通过智能技术生成

I have got a table that is a result of a (My)SQL query. In this table I have the post creation timestamp and the user comment creation timestamp. The trick is that not all posts have a comment (so some comment_creation are NULL).

I would like to order the rows according of the most recent creation time of the post or user comment.

How can I get the max(post_creation, comment_creation) of each row and order them (DESC order)?

Thanks for all contribution.

解决方案

Based on your previous question, try:

SELECT p.id AS post_id,

p.author_id AS post_author_id,

p.created_date AS post_created,

c.author_id AS comment_author_id,

c.created_date AS comment_created,

p.title,

c.content,

coalesce(c.created_date,p.created_date) AS sort_date

FROM Posts p

LEFT JOIN Comments c ON p.id = c.post_id

WHERE p.author_id = $userId

UNION ALL

SELECT p.id AS post_id,

p.author_id AS post_author_id,

p.created_date AS post_created,

c.author_id AS comment_author_id,

c.created_date AS comment_created,

p.title,

c.content,

c.created_date AS sort_date

FROM Posts p

RIGHT JOIN Comments c ON p.id = c.post_id

WHERE c.author_id = $userId

ORDER BY sort_date

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值