0

我想获取今天日期前后 3 天生日的用户列表。我的意思是,如果今天是March 2,2013,我想让有生日的用户Feb 27,2013开始March 5,2013. 这是我的数据库设计。

用户表

id | name | birth_day | birth_month | birth_year

我无法再更改数据库设计,因为我无法访问它,并且更改设计只会在网站发生巨大变化时发生。

这是我当前的代码:

if (empty($date))
            $date = date('Y-m-d'); // now

        $start_date = strtotime($date.' -'.$day_range.' day');
        $end_date = strtotime($date.' +'.$day_range.' day');
        $start_month = date('m', $start_date);
        $end_month = date('m', $end_date);
        $start_day = date('d', $start_date);
        $end_day = date('d', $end_date);

        if ($start_day > $end_day) {
            $tmp = $start_day;
            $start_day = $end_day;
            $end_day = $tmp;
        }

        /* This is a dirty fix for getting birthdays between dates */
        $this->User->contain(array('User' => array('first_name', 'last_name', 'userstatus_id')));
        $user = $this->User->find('all', array(
            'conditions' => array(
                'User.birth_month BETWEEN ? AND ?' => array($start_month, $end_month),
                'User.birth_day BETWEEN ? AND ?' => array($start_day, $end_day),
            ),
            'fields' => array(
                'birth_year',
                'birth_day',
                'birth_month'
            ),
            'order' => array(
                'birth_month' => 'ASC',
                'birth_day' => 'ASC'
            )
        ));

        foreach($user as $k => $v) {
            $temp = strtotime(date('Y-'.$user[$k]['User']['birth_month'].'-'.$user[$k]['User']['birth_day']));

            if ($temp >= $start_date && $temp <= $end_date) {
            }
            else {
                unset($user[$k]);
            }

        }
4

2 回答 2

5

如果您无法更改表格设计,那么我将从三列创建一个日期时间,然后将其用于过滤器:

select *
from 
(
  select id, name,
    str_to_date(concat(year(now()), '-', birth_month, '-', birth_day), '%Y-%m-%d') birthdate
  from users
) d
where birthdate >= '2013-02-27'
  and birthdate <= '2013-03-05'

请参阅SQL Fiddle with Demo

这使用STR_TO_DATE()CONCAT()函数将生日创建为日期数据类型。一旦你有了日期,你就可以应用你的日期过滤器。

于 2013-03-01T16:11:20.443 回答
0

您需要按字母顺序获取日期,以便查询年月日。问题在于月初和月底的重叠。使用MySQL 日期格式选项,您可以连接日期并将它们转换为日期对象以进行搜索。如果您有很多行,这将很慢并且效率不高,因为必须评估每一行。

另一种方法是查询您已经拥有的列,但使用从应用程序逻辑得出的范围条件并生成内联 SQL,例如

SELECT * FROM users
WHERE 1=1

然后:

AND birth_year = X

或重叠范围

AND (birth_year = X OR birth_year = Y)

对birth_month 和birth_day 执行相同操作

Not an elegant solution, but given your poor schema design I can only see one of these two alternatives. The first is easier but the 2nd should generally perform better provided the query isn't performing a full table scan - if you're not indexing then just use the string to date option.

于 2013-03-01T16:19:46.980 回答