MySQL找到所有未在六个月或更长时间内预约的人

时间:2011-05-19 22:28:11

标签: mysql

大家好我有一个约会表,其中包含记录约会日期的DATE字段。 show create语句如下。

 | groomappointments | CREATE TABLE `groomappointments` (
   `gapmtDate` date NOT NULL,
   `gapmtClient` int(11) NOT NULL,
   `gapmtUser` int(11) NOT NULL,
   `gapmtStatus` int(11) NOT NULL DEFAULT '1',
   `gapmtSTime` time NOT NULL,
   `gapmtETime` time NOT NULL,
   `gapmtPet` int(11) DEFAULT NULL,
   `gapmtService` int(11) DEFAULT NULL,
   `gapmtTracker` int(11) NOT NULL AUTO_INCREMENT,
   PRIMARY KEY (`gapmtDate`,`gapmtClient`,`gapmtUser`,`gapmtStatus`,`gapmtSTime`),
   KEY `gappPet` (`gapmtPet`),
   KEY `gappClient` (`gapmtClient`),
   KEY `gappSrve` (`gapmtService`),
   KEY `gappStat` (`gapmtStatus`),
   KEY `gappUsr` (`gapmtUser`),
   KEY `gapmtTracker` (`gapmtTracker`),
   CONSTRAINT `gappClient` FOREIGN KEY (`gapmtClient`) REFERENCES `clients` (`clientid`) ON DELETE NO ACTION ON UPDATE NO ACTION,
   CONSTRAINT `gappPet` FOREIGN KEY (`gapmtPet`) REFERENCES `pets` (`petID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
   CONSTRAINT `gappSrve` FOREIGN KEY (`gapmtService`) REFERENCES `groomservices` (`groomServicesID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
   CONSTRAINT `gappStat` FOREIGN KEY (`gapmtStatus`) REFERENCES `aptstatus` (`aptStatusID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
   CONSTRAINT `gappUsr` FOREIGN KEY (`gapmtUser`) REFERENCES `users` (`userID`) ON DELETE NO ACTION ON UPDATE NO ACTION
  ) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=latin1 |

我正在尝试查询数据库,以查找过去六个月或更长时间内记录最后一次约会的所有客户,但我无法找出正确的查询。

我已经尝试了以下查询,它将为我提供过去记录的6Mts +的所有记录,但包括在过去一周,一个月内有约会的客户等。

 mysql> select groomappointments.gapmtDate, clients.firstname, clients.lastname
-> from groomappointments,clients
-> WHERE date_sub(CURDATE(), INTERVAL 6 MONTH)>gapmtDate
-> AND clients.clientid = groomappointments.gapmtClient;

任何想法都非常感激。

2 个答案:

答案 0 :(得分:1)

您需要获取最长约会日期,然后查看是否> 6个月前,还是根本没有。如

select appt.lastDate, clients.firstname, clients.lastname
from (select max(gapmtDate) as lastDate,gapmtClient from groomappointments group by gamptClient) as appt ,clients 
where date_sub(CURDATE(), INTERVAL 6 MONTH)>lastDate
AND clients.clientid = appt.gapmtClient;

未经测试,但应该有效。或者至少给你一个起点。

答案 1 :(得分:1)

select clients.firstname, clients.lastname, groomappointments.gapmtDate
from clients join groomappointments on clients.clientid = groomappointments.gapmtClient
where clients.clientid in (
  select gapmtClient from groomappointments
  group by gapmtClient
  where date_sub(CURDATE(), INTERVAL 6 MONTH) > gapmtDate
)