How to select the max of two element of each row in MySQL

人盡茶涼 提交于 2019-12-25 00:33:16

问题


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.


回答1:


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



回答2:


Given your table looks something like this...

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;

...the SELECT-query could be done like this:

SELECT IF(comment_creation > post_creation, 
          comment_creation, 
          post_creation) AS sortorder,
       id
FROM yourtable
ORDER BY sortorder DESC;


来源:https://stackoverflow.com/questions/9532140/how-to-select-the-max-of-two-element-of-each-row-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!