GROUP BY效果不佳

时间:2014-09-28 09:11:14

标签: php mysql sql

你好我有一张表:

id_order | id_order_history | date_add

通过此查询,我可以获得所有id_order_history = 3(准备中)

的订单
    SELECT 
        `oh`.`id_order`
    FROM (
        SELECT MAX( `date_add` ) AS date_add
        FROM `'._DB_PREFIX_.'order_history`
        GROUP BY `id_order`
    ) AS h
    INNER JOIN 
        '._DB_PREFIX_.'order_history AS oh 
    ON 
        `h`.`date_add` = `oh`.`date_add`
    INNER JOIN 
        '._DB_PREFIX_.'orders AS o
    ON 
        `oh`.`id_order` = `o`.`id_order`';

    $sql .= 'WHERE
        oh.`id_order_state` = '.$status.''; 
    $sql .= ' AND  
        oh.date_add >= "'.$start.'"';
    $sql .= ' AND  
        oh.date_add <= "'.$end.'"
    ORDER BY 
        `oh`.`id_order` ASC

问题在于,对于某些订单,SELECT MAX无法获得date_add的正确值

id_order | id_order_history | date_add

1        | 5                | 25-09-2014 18:07:59 ---> this is the correct value
1        | 4                | 25-09-2014 18:07:51
1        | 3                | 25-09-2014 18:06:42 ---> but query return this

如果我在1秒(18:06:43)添加日期,查询将返回正确的值25-09-2014 18:07:59

我无法弄清楚如何解决问题。

我已经读过,有时候GROUP BY会把结果看得很高兴......

我该如何解决?

1 个答案:

答案 0 :(得分:0)

将您的列date_add转换为ISO日期时间字符串和/或使用TO_SECONDS(请参阅MySQL doc here

 ...( SELECT FROM_UNIXTIME(MAX(TO_SECONDS(`date_add`)) ) AS date_add
    FROM `'._DB_PREFIX_.'order_history`
    GROUP BY `id_order` ) AS h