排序MySQL`date`结果时的奇怪问题

时间:2013-08-18 08:37:09

标签: mysql date sorting

当我查询我的桌子以显示即将到来的生日(下面的架构和查询),然后按日期排序时,我会得到一些奇怪的结果。 dob(出生日期)字段的类型为date,格式为0000-00-00

我正在使用以下架构:

People:
+------------+-------------+------+-----+-------------------+----------------+
| Field      | Type        | Null | Key | Default           | Extra          |
+------------+-------------+------+-----+-------------------+----------------+
| id         | int(11)     | NO   | PRI | NULL              | auto_increment |
| fname      | varchar(32) | NO   |     | NULL              |                |
| lname      | varchar(32) | NO   |     | NULL              |                |
| dob        | date        | NO   |     | 0000-00-00        |                |
| license_no | varchar(24) | NO   |     | NULL              |                |
| date_added | timestamp   | NO   |     | CURRENT_TIMESTAMP |                |
| status     | varchar(8)  | NO   |     | Allow             |                |
+------------+-------------+------+-----+-------------------+----------------+

这是我的查询,因为它是从PHP调用的:

<?php   
/* This will give us upcoming dobs for the next 2 weeks */
$con = connect_db();
// grab any dobs coming up in the next week and sort them by what's 
//coming up first
//if they are born on Feb. 29th, it will fall on March 1st
$query = 'select p.lname, p.fname, u.number, p.dob ' . 
         'from people p, units u where p.id = u.resident and ' .
         'DAYOFYEAR(curdate()) <= DAYOFYEAR(DATE_ADD(dob, INTERVAL ' .
         '(YEAR(NOW()) - YEAR(dob)) YEAR)) AND DAYOFYEAR(curdate()) +30 >= ' .
         'dayofyear(`dob`) order by dayofyear(dob) limit 7;';

$result = mysqli_query($con, $query);
if (!empty($result)) {
        while($row = mysqli_fetch_array($result)) {
                $fname = $row['fname'];
                $lname = $row['lname'];
                $number = $row['number'];
                $dob = date("m-d", strtotime($row['dob']));
                if($dob == date("m-d")) {
                        $dob = 'Today!';
                        printf('%s, %s</br>Unit: %s</br>%s</br></br>', $lname, 
                               $fname, $number, $dob);
                } else {
                       printf('%s, %s</br>Unit: %s</br>Date: %s</br></br>', $lname,
                              $fname, $number, $dob);
                }       
        }       
 }       
?>      

这是返回查询的示例:

Name, Name
Unit: 110
Date: 09-11

Name2, Name2
Unit: 434
Date: 09-10

如你所见,订单错了!

编辑 - 现在我注意到有问题的记录(上面的两个日期)在MySQL中没有正确排序曾经

其中一个完整日期是:1950-09-11 另一个是:1956-09-10

我查看了这两个记录并且没有找到任何损坏的数据,所以我很困惑为什么会发生这种情况

1 个答案:

答案 0 :(得分:0)

ORDER BY dayofyear(dob)ASC

祝你好运