Looking to run a query using multiple left joins. The following query works.
SELECT directory.location, sales.covers, labor.hours
FROM t_directory directory
LEFT JOIN t_sales sales
ON sales.id = directory.id
AND sales.business_date = '2011-11-14'
LEFT JOIN t_labor labor
ON labor.id = directory.id
AND labor.business_date = '2011-11-14'
ORDER BY directory.id ASC
The trouble comes if I try to query between a date range. Adding a Group By clause has been duplicating rows. Right now I’m actually using two separate queries, which is probably better practice, and a better solution. This is just out of pure curiosity at this point.
Here is what I have so far.
SELECT directory.location, sales.covers, labor.hours
FROM t_directory directory
LEFT JOIN t_sales sales
ON sales.id = directory.id
AND sales.business_date BETWEEN '2011-11-13' AND '2011-11-14'
LEFT JOIN t_labor labor
ON labor.id = directory.id
AND labor.business_date BETWEEN '2011-11-13' AND '2011-11-14'
GROUP BY directory.id, sales.business_date, labor.business_date
ORDER BY directory.id ASC
Clearly something wrong with my GROUP BY clause, and perhaps other errors as well.
I am looking for a result like this:
| location | covers | labor |
=============================
loc1 | 300 | 99.40
loc1 | 325 | 100.50
loc2 | 250 | 89.00
loc2 | 275 | 90.20
loc3 | 400 | 100.00
loc3 | 500 | 122.90
And of course, what I am actually getting is:
| location | covers | labor |
=============================
loc1 | 300 | 99.40
loc1 | 300 | 100.50
loc1 | 325 | 99.40
loc1 | 325 | 100.50
loc2 | 250 | 89.00
loc2 | 250 | 90.20
loc2 | 275 | 89.00
loc2 | 275 | 90.20
loc3 | 400 | 100.00
loc3 | 400 | 122.90
loc3 | 500 | 100.00
loc3 | 500 | 122.90
Any help with getting the expected results would be greatly appreciated.
EDIT:
Here are the tables with sample data that I want to join. They all share a common id.
t_directory
| *id | location |
|100 | loc1 |
|101 | loc2 |
|102 | loc3 |
t_sales
| business_date | id | sales | covers |
| 2011-11-13 | 103| 4000.00 | 300 |
| 2011-11-14 | 103| 4050.00 | 325 |
t_labor
|business_date | id | hours |
| 2011-11-13 | 103| 99.40 |
| 2011-11-14 | 103| 100.50|
Your expected result doesn’t really make sense to me. There’s no relationship between
salesandlaborrows, so why should acoversvalue of 300 go next to alaborvalue of 99.40? What’s tying those two values together? That’s why you’re finding it hard to write the query to produce the results: you’re trying to output two columns where the data in each are not related.I probably haven’t explained that very well. I’m sure someone else can!