我的桌子结构是这样的
TBL客户
clientid
clientname
技术设施
facilityid
facilityname
TBL客户设施
clientid
facilityid
moveindate
我允许我的用户输入未来日期作为入住日期,我要做的是选择我的客户机所在的当前设施。我试过了
SELECT
clientid,
facilityid,
moveindate
FROM
tblclientfacilities
WHERE
MAX(tblclientfacilities.moveindate) <= now()
GROUP BY
tblclientfacilities.clientid
显然那不管用。有人能帮我找到正确的方向吗?谢谢!
最佳答案
SELECT clientId,
(
SELECT facilityId
FROM tblclientfacilities cf
WHERE cf.clientId = c.clientId
AND cf.moveDate <= NOW()
ORDER BY
cf.clientId DESC, moveDate DESC
LIMIT 1
) AS currentFacility
FROM tblclients c
在
tblclientfacilities (clientId, moveDate, facilityId)
上创建一个唯一的索引以使其快速工作。关于mysql - SQL选择将来不再存在的最大记录,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15794026/