Doctrine2选择生日范围

时间:2011-05-31 12:37:05

标签: mysql sql

我想选择即将到来的5天过生日的所有员工。生日保存在日期字段中。感觉就像我必须使用之间,但是年份范围会破坏结果。

基本上我想在5天的范围内按月和日选择日期。

数据库方案:

CREATE TABLE IF NOT EXISTS `tbl_office_employee` (
  `id` int(11) NOT NULL auto_increment,
  `firstname` varchar(256) collate utf8_unicode_ci default NULL,
  `surname` varchar(256) collate utf8_unicode_ci default NULL,
  `birthdate` date NOT NULL,
  `telephone` varchar(256) collate utf8_unicode_ci default NULL,
  PRIMARY KEY  (`id`)
)

有人知道一个查询来完成此任务吗?

3 个答案:

答案 0 :(得分:4)

你想在MySQL中使用这样的东西(已编辑 - 真正的工作示例):

SELECT *
FROM `tbl_office_employee` e 
WHERE FLOOR(
        (
            UNIX_TIMESTAMP(
                CONCAT(
                    YEAR(CURDATE()) + (DATE_FORMAT(e.birthdate, '%m-%d') < DATE_FORMAT(CURDATE(), '%m-%d')),
                    DATE_FORMAT(e.birthdate, '-%m-%d'))) 
            - UNIX_TIMESTAMP(CURDATE()))
        / 86400) < 5

下面写的SQL查询没有选择明年的生日(即1月1日至1月31日),所以请使用上面的一个...

  

SELECT * FROM tbl_office_employee e WHERE UNIX_TIMESTAMP(DATE_FORMAT(e.birthdate,CONCAT(YEAR(CURDATE()),' - %m-%d')))在UNIX_TIMESTAMP(CURDATE())和UNIX_TIMESTAMP之间(DATE_ADD(CURDATE(),INTERVAL 5 D))

我必须使用UNIX_TIMESTAMP,因为日期变化,即5月31日至6月5日(5不大于31),并在e.birthdate更改年份。< / EM>


可以在DQL(Doctrine 1)中完成:

Doctrine_Query::create()
    ->select('e.firtsname')
    ->from('tbl_office_employee e')
    ->where('e.date BETWEEN ? AND ?', array($today_date, $date_plus_5_days))
    ->getSqlQuery();

哪个输出基本相同。

我不认为开箱即用的DQL可以DATE_ADD,但是there is chapter called DQL User Defined Functions in docs, which has example implementation of DATE_ADD function for MySQL

答案 1 :(得分:1)

SELECT * FROM member WHERE DATE_FORMAT(birthdate, '%m%d') between DATE_FORMAT(NOW(), '%m%d') and date_format(adddate(now(), interval 4 day),'%m%d');

SELECT * FROM member WHERE DATE_FORMAT(`birthdate`, '%m%d') >= DATE_FORMAT(NOW(), '%m%d') AND DATE_FORMAT(`birthdate`, '%m%d') <= DATE_FORMAT(DATE_ADD(NOW(), INTERVAL 4 DAY), '%m%d') ORDER BY DATE_FORMAT(`birthdate`, '%m%d') ASC;

SELECT   * FROM member WHERE   (1 =   (FLOOR(DATEDIFF(DATE_ADD(DATE(NOW()),INTERVAL   4 DAY),birthdate) / 365.25)) -(FLOOR(DATEDIFF(DATE(NOW()),birthdate)   / 365.25))) ORDER BY MONTH(birthdate),DAY(birthdate)

所有查询都经过测试。

答案 2 :(得分:0)

嗯......我还没有测试过,但可以尝试一下......

SELECT *, 
CURRENT_DATE() + INTERVAL 5 DAY AS coming_date,
CURRENT_DATE() AS today_date
FROM tbl_office_employee
WHERE birthdate <= coming_date AND birthdate >= today_date