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;
任何想法表示赞赏。     

解决方法

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
)
    ,您需要获取最大约会日期,然后查看> 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;
未经测试,但应该可以。或至少给您一个起点。