Simple INNER JOIN Query Returns No Value - Where Did i Go Wrong?
The query below fetches the wageTypeID based on the current active hiring info record and salary record.
SELECT wt.wageTypeID
FROM TimeSheet t
INNER JOIN Employee e ON e.employeeID = t.employeeID
INNER JOIN Salary s ON s.salaryID = t.salaryID
INNER JOIN Wage w ON w.wageID = s.wageID
INNER JOIN EmpHiringInfo ehf ON ehf.EmpHiringInfoID = s.EmpHiringInfoID
INNER JOIN WageType wt ON wt.wageTypeID = w.wageTypeID
WHERE ehf.employeeID = 300
AND ehf.isActive = 1
AND s.isActive = 1
The above query should return the value 15! I wonder where did i go wrong?
Here is the schema of the joined tables:
TimeSheet:
timeSheetID
employeeID - 300
salaryID
.
.
Salary:
salaryID
EmpHiringInfoID
wageID
isActive - true
.
.
WageType:
wageTypeID - 15
wageTypeTitle - Hourly
Wage:
wageID
wageTypeID - 15
wageAmount - $11
EmpHiringInfo:
EmpHiringInfoID
employeeID
isActive - true
.
.
The isActive in Sala开发者_如何学Cry is only and only True for one record. Same thing applied to EmpHiringInfo.
Try commenting out one join and see if you get any results back, if not comment out another and so on until you start seeing results. The last one you commented out might give you a clue as to why its failing.
Without an actual data dump (and the create table statements), we can't exactly say because we can't see your data. So here's how to approach the situation so you can find out where the issue is:
- Scale back the SELECT statement to have no JOINs--you want to make sure the base table returns the record(s) you need before going any further.
- Add a JOIN, one at a time. Each JOIN you add, you need to check the resultset to see that the rows you're expecting are still visible. If a JOIN has more than one criteria (IE:
ehf
), then again--incrementally add criteria while checking every time.
Eventually, the criteria that is causing the issue will become obvious and so you'll have to review how to handle the situation. It's possible more than one JOIN is causing troubles, and you might not see the others until after one is addressed.
I recommend restructuring your query to use the table you're selecting the most data from in the FROM clause. In this case, that means:
SELECT wt.wageTypeID
FROM WAGETYPE wt
That will make adding JOINs easier.
Look at the actual execution plan. Mouse over the arrows. Look and see where the number of rows returned from a JOIN becomes zero.
Rebuild the Select SQL a join at a time, starting with EmpHiringInfo and Salary, since those are the core ones referenced in your where clause.
精彩评论