我认为我非常接近这个查询,但似乎无法破解它,而且我不确定我是否拥有最有效的方法。
我试图找到用户在预订的一系列日期中没有被预订的一天。
考虑人员安排。我需要找到谁可以在周二工作,以及谁在本周的其他日子工作。
我的查询目前看起来像这样
SELECT employees.uid, name, date
FROM employees
LEFT JOIN storelocation ON employees.uid = storelocation.uid
LEFT JOIN schedule ON emplyees.uid = schedule.uid
WHERE slid =9308
AND date
BETWEEN '2009-11-10'
AND '2009-12-20'
AND NOT
EXISTS (
SELECT uid
FROM schedule
WHERE date = '2009-11-11'
)
如果我不包含“不存在”,我会得到 1500 个结果
如果我仅使用“不存在”形式的选择,我会得到 200 个结果,因此这两个查询都是独立工作的。
但是,我编写的查询返回 0 结果。
I think I'm pretty close on this query, but can't seem to crack it, and I'm not sure if I've got the most efficient approach.
I am trying to find a day where a user is not booked from a range of dates where they are booked.
Think staff scheduling. I need to find who is available to work on Tuesday, and is working on other days this week.
My query currently looks like this
SELECT employees.uid, name, date
FROM employees
LEFT JOIN storelocation ON employees.uid = storelocation.uid
LEFT JOIN schedule ON emplyees.uid = schedule.uid
WHERE slid =9308
AND date
BETWEEN '2009-11-10'
AND '2009-12-20'
AND NOT
EXISTS (
SELECT uid
FROM schedule
WHERE date = '2009-11-11'
)
If I don't include the 'Not Exists', I get 1500 results
If I use only the Select form the 'Not Exists', I get 200 results, so both of those queries work independently.
However, my query as I've written it returns 0 results.
发布评论
评论(2)
您可能想尝试更多类似这样的事情:
You might want to try something more like this:
问题是您的
NOT EXISTS
不相关,如果不使用表别名,您将无法执行此操作:EXISTS< 中的
SELECT
/code> 子句不做任何事情 - 您可以使用EXISTS( SELECT 1/0 ...
,这应该导致“不能被零除”错误。但它不会...EXISTS
仅在 1+ 个实例与 WHERE/etc 子句匹配时才返回 true 如果您愿意,有很多问题询问 SELECT 子句中的内容是否重要。阅读更多内容,撇开拼写错误不谈,MySQL 应该比我提供的替代方案更快。要了解更多原因,请查看这篇文章:NOT IN 与 NOT EXISTS 与 LEFT MySQL 中的 JOIN/IS NULL。
The problem is your
NOT EXISTS
isn't correllated, and you won't be able to do with this without using table aliases:The
SELECT
in anEXISTS
clause doesn't do anything - you could useEXISTS( SELECT 1/0 ...
, which should cause a "can not divide by zero" error. But it won't...EXISTS
only returns true if 1+ instances match the WHERE/etc clause. There are numerous questions on SO asking about if it matters what's in the SELECT clause if you want to read more.Jim's answer, typo aside, should be faster in MySQL than the alternative I supplied. To read more about why, check this article: NOT IN vs NOT EXISTS vs LEFT JOIN/IS NULL in MySQL.