所以我有2张桌子照顾和客户,就像这样
client {
id,name
}
caring {
id,startDate,endDate,clientId
}
我需要让所有在两个提供的日期之间至少有一天可用的客户,您可以看到我的屏幕截图作为参考.
截图我有两个客户端,我需要返回它们.如您所见,第一个客户在提供期间(16.5.-29.5.)之间有三个免费日(21.5.-23.5.),而第二个客户没有任何关怀期.
到目前为止,我尝试过这样的事情
SELECT * FROM client cl
WHERE cl.id NOT IN (SELECT clientId FROM caring
WHERE endDate >= CURDATE() AND endDate <= DATE_ADD(CURDATE(),INTERVAL 14 DAY))
这个只返回没有照顾的客户.这部分是我需要的,因为此查询不包括我的屏幕截图中的第一个客户端.然后我尝试了下面的查询.
SELECT ca.startDate,ca.endDate,cl.firstName,cl.lastName
FROM caring ca
LEFT JOIN client cl on cl.id = ca.clientId
WHERE ca.startDate NOT IN (
SELECT endDate
FROM caring
) AND ca.startDate <= '2017-05-29' AND ca.endDate >= '2017-05-16'
但我没有得到理想的结果.
任何想法我怎么能实现这一点,提前thx!
最佳答案
选择感兴趣的期间的关怀并分别限制此期间的开始/结束日期.这种限制将允许更容易计算“已预订”,即以后不是免费的日子.
原文链接:https://www.f2er.com/mysql/432886.htmlSELECT ca.id,-- Limit start/end dates to period of interest,respectively
GREATEST (ca.startDate,'2017-05-16') AS `effectiveStartDate`,LEAST (ca.endDate,'2017-05-29') AS `effectiveEndDate`,ca.clientId
FROM carings ca
WHERE ca.startDate <= '2017-05-29' AND ca.endDate >= '2017-05-16';
接下来,计算预订天数:
DATEDIFF (DATE_ADD (LEAST (ca.endDate,'2017-05-29'),INTERVAL 1 DAY),GREATEST (ca.startDate,'2017-05-16'))
AS `effectiveDays`
最后,过滤掉整个期间预订的客户.这是通过比较完成的
>每个客户(GROUP BY)的预订天数总和
>整个期间的天数(具有sumDays< DATEDIFF(...)).
你也想要整个期间都没有预订的客户,我建议从客户表开始,“只是”LEFT JOIN(有效)关注:
SELECT cl.id,cl.name,IFNULL (SUM (eca.effectiveDays),0) AS `sumDays`
FROM clients cl
LEFT JOIN
(SELECT ca.id,respectively
GREATEST (ca.startDate,DATEDIFF (
DATE_ADD (LEAST (ca.endDate,'2017-05-16'))
AS `effectiveDays`,ca.clientId
FROM carings ca
WHERE ca.startDate <= '2017-05-29' AND ca.endDate >= '2017-05-16')
eca -- effectiveCarings
ON eca.clientId = cl.id
GROUP BY cl.id,cl.name
HAVING sumDays <
DATEDIFF (DATE_ADD ('2017-05-29','2017-05-16')
ORDER BY cl.id;