views:

63

answers:

2

I have a table of employees and their schedule, like so:

Emp_Name | Date
--------  -----
Smith    | 08-01-2009
Jones    | 08-01-2009
Goodman  | 08-02-2009
Smith    | 08-02-2009
Jones    | 08-02-2009
Goodman  | 08-03-2009

How would I write a query so that the results were only employee names of employees working on 08-02-2009 and 08-03-2009.

I'm getting caught up because all I can think of are ways to get the names for EITHER match, but I can't seem to find the right way to get the results for only the names that have matches for all search criteria across multiple rows.

So based on the example conditions, I should only get Goodman. But if I do a query like WHERE Date IS (list of dates) I would get Goodman and Smith and Jones, since Smith and Jones both work on 08-02-2009. If I try to do some kind of JOIN, I would not always end up with equal columns, since the number of days each employees works is variable.

I thought Union might be the way to go, but I wouldn't always know how may conditions someone was searching by.

+2  A: 

Here's my first stab at it, there's probably a more efficient way than using HAVING though...

SELECT Emp_Name,COUNT(DISTINCT date) as daycount 
FROM employee 
WHERE date IN ('08-01-2009', '08-02-2009')
GROUP BY Emp_Name
HAVING daycount=2
Paul Dixon
No need to select the count and you can use an IN instead of the OR, but I think this is as good as you can get
Vinko Vrsalovic
I put the count in the output as I thought it would illustrate what was going on. You're write about using IN though, have modified it.
Paul Dixon
Is there a way to pass the number of search parameters as a variable to the HAVING part (outside of scripting it exterior to the query)? This is really good, by the way.
Anthony
Oh, and what if I wanted, say, all employees working on one given set of days, but take out any who are working on some other given day? Or employees working at least 2 of 3 days given? I don't expect the code. I'm just trying to suggest alternatives which complicate the scenario and thus reflect why I thought this would be a tad more built-in to MySQL.
Anthony
For the "at least" part of the last comment, I suppose that's pretty easy. Just change the HAVING clause from a `=` to a `>`. And the "not working on this date" can be done by adding a "AND date NOT IN" bit to the WHERE clause, right?
Anthony
A: 

If you don't need a generic solution, you can use this:

select Emp_Name
from employee
where Emp_Name
  in (select Emp_Name from employee where Date = '08-02-2009')
  and in (select Emp_Name from employee where Date = '08-03-2009')
  ...
Zed
I thought of something like that. The only problem is that it gets clumsy if I don't know the number of dates up front. I'd have to script the query in pieces. Which isn't tragic, I just figured there was a way to do this type of query native to MySQL.
Anthony