MySQL按值和最大日期分组

时间:2015-04-17 00:04:21

标签: php mysql

我需要提取列result_1和result_2的最后一个字符并对它们进行分组,以便我有一个从0到9的列表,指示它何时生成。 在下面的代码中,我设法获得了一个从0到9的列表,但日期是表中最早的日期而不是最新日期。

$sql = "SELECT * FROM ((SELECT RIGHT(result_1, 1) AS results, date 
    FROM act_results ORDER BY date ASC) 
    UNION ALL (SELECT RIGHT(result_2, 1) AS results, date 
    FROM act_results)) s WHERE results != ''";

$sql .= " GROUP BY results";

$table = mysql_query($sql);

while ($row = mysql_fetch_array($table)) {
   echo $row['results']." (".$row['date'].") <br>";
}

任何想法如何解决? 提前谢谢。

1 个答案:

答案 0 :(得分:1)

group bymax()

一起使用
SELECT results, max(date)
FROM ((SELECT RIGHT(result_1, 1) AS results, date
       FROM act_results
      ) UNION ALL
      (SELECT RIGHT(result_2, 1) AS results, date
       FROM act_results
      )
     ) s
WHERE results <> ''
GROUP BY results;