MySQL - ORDER BY STR_TO_DATE无效

时间:2014-06-13 10:05:52

标签: php mysql sql-order-by str-to-date

我正在尝试使用PHP和MySql运行PDO查询,然后按日期对其进行排序。

我的查询如下:

    $query_params = array( 
        ':website' => $site
    );

    $query = " 
        SELECT 
            DATE_FORMAT(date, '%d/%m/%Y') AS date,
            id
        FROM
            items as bi
        INNER JOIN 
            basket as bb ON bi.item_number=bb.basket_item
        INNER JOIN
            orders as bo ON bb.basket_order=bo.order_number 
        WHERE
            bi.website = :website
        ORDER BY 
            STR_TO_DATE(date,'%d/%m/%Y') DESC
    "; 

    try { 
        $stmt = DB::get()->prepare($query); 
        $stmt->execute($query_params); 
        $rows = $stmt->fetchAll();
    } 
    catch(PDOException $ex) {} 

    foreach($rows as $row):
        $output .= "".$row["date"].",";
        $output .= "".$row["id"].",";
        $output .= "\r\n <br />";
    endforeach;

我的输出应该是:

13/06/2014, 8676,
12/06/2014, 5765,
12/04/2014, 7683, 
08/12/2013, 1098, 
06/12/2013, 2003, 
06/12/2013, 6755,

它似乎没有按任何方式排序:

12/06/2014, 5765,
12/04/2014, 7683, 
13/06/2014, 8676, 
06/12/2013, 2003, 
06/12/2013, 6755, 
08/12/2013, 1098,

STR_TO_DATE(date,'%d/%m/%Y') DESC是否应按预期排序?

2 个答案:

答案 0 :(得分:2)

你的桌子上已经有了一个可爱的日期栏 - 为什么在地球上尝试按照那种格式化的字符串进行排序?

    SELECT 
        DATE_FORMAT(date, '%d/%m/%Y') AS date,
        id
    FROM
        items as bi
    INNER JOIN 
        basket as bb ON bi.item_number=bb.basket_item
    INNER JOIN
        orders as bo ON bb.basket_order=bo.order_number 
    WHERE
        bi.website = :website
    ORDER BY 
        date DESC

当然,根据您的喜好将日期输出格式化为用户 - 但是您不仅要通过格式化每一行数据然后按照数据库本地完成的内容进行排序来使数据库执行更多操作。意思是。

编辑:有趣。我想知道date是否是一个半保留字的事实是否导致你的排序不按预期发生?

也许试试这个:

    ORDER BY 
        bo.date DESC

答案 1 :(得分:1)

试试这个

$query = " 
    SELECT 
        DATE_FORMAT(date, '%d/%m/%Y') AS date,
        id
    FROM
        items as bi
    INNER JOIN 
        basket as bb ON bi.item_number=bb.basket_item
    INNER JOIN
        orders as bo ON bb.basket_order=bo.order_number 
    WHERE
        bi.website = :website
    ORDER BY 
        date DESC
";