【问题标题】:How to select the max of two element of each row in MySQL如何在MySQL中选择每行的两个元素的最大值
【发布时间】:2012-03-03 00:46:43
【问题描述】:

我有一个表,它是 (My)SQL 查询的结果。在此表中,我有帖子创建时间戳和用户评论创建时间戳。诀窍是并非所有帖子都有评论(所以有些 comment_creation 是 NULL)。

我想根据帖子或用户评论的最近创建时间对行进行排序。

如何获取每行的max(post_creation, comment_creation) 并对其进行排序(DESC order)?

感谢所有贡献。

【问题讨论】:

  • 我假设comment_creation(如果存在)总是大于post_creation
  • 确实如此。但是我们首先要检查comment_creation是否存在。

标签: sql timestamp blogs max


【解决方案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

【讨论】:

【解决方案2】:

鉴于您的桌子看起来像这样......

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-query 可以这样完成:

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

【讨论】:

  • 您的回答似乎很有趣。但它涉及两个值之间的比较:Max(A,B)。那么两个以上的值呢:Max(A1,A2,...,An)?有没有(My)SQL 函数?
  • 请提供更多详细信息,您的桌子是什么样子的。 MAX() 是一个聚合函数,用于比较不同的行,而不是不同的字段。
  • 让我们考虑一个有 N 个科目(数学、生物……)的学者班。每一行(在我的数据库中)都是一个学生,每一列都是一个主题。然后,我数据库中的每个字段都包含一个学生的科目分数。如何获得每个学生的最高分和对应的科目?
  • 这不太像问题。对于这个,我会使用另一种数据库方法。三张表:studends、classes 和 score 表。然后,您可以使用群组、加入等方式来实现您想要的目标。
猜你喜欢
  • 1970-01-01
  • 2020-02-09
  • 1970-01-01
  • 2018-10-27
  • 2014-08-24
  • 2013-10-27
  • 1970-01-01
  • 2021-11-22
  • 2013-04-03
相关资源
最近更新 更多