0

当我查询我的表格以显示即将到来的生日(下面的模式和查询)时,我得到了一些奇怪的结果,然后首先按日期排序,即将到来的日期。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

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

4

1 回答 1

0

ORDER BY dayofyear(dob) ASC

祝你好运

于 2013-08-18T08:48:41.373 回答