我有一个表是(My)SQL查询的结果。在此表中,我有帖子创建时间戳和用户评论创建时间戳。诀窍是并非所有帖子都有评论(所以有些comment_creation
是NULL)。
我想根据帖子或用户评论的最近创建时间来排序。
如何获取每一行的max(post_creation, comment_creation)
并订购它们(DESC
订单)?
感谢您的所有贡献。
答案 0 :(得分:1)
根据您之前的问题,请尝试:
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
答案 1 :(得分:0)
鉴于你的表看起来像这样......
CREATE TABLE `yourtable` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`post_creation` timestamp NULL DEFAULT NULL,
`comment_creation` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM;
... SELECT
- 查询可以这样完成:
SELECT IF(comment_creation > post_creation,
comment_creation,
post_creation) AS sortorder,
id
FROM yourtable
ORDER BY sortorder DESC;