Reply
Tue 14 Sep, 2004 10:07 pm
I'm having trouble figuring out how to use SQL to select when there are multiple levels of keys that link tables together.
For example, look at the following table structure in a database:
tblUserDepartments
field: deptID
field: userID
tblUserInfo
field: userID
field: userName
field: activityID
tblActivityPlan
field: activityID
field: activityName
field: plannedCount
field: actualCount
Now, I want to specify a deptID, and have it find each user that is in that department, and then find each activity plan for each user, and then create a record for each distinct activity...showing the planned and actual count for those activities.
Example desired recordset output:
UserName | ActivityName | Planned Count | Actual Count
Joe Smith | Social Work | 4 | 2
Joe Smith | Other Work | 3 | 3
Margaret R | Freel Work | 5 | 6
I don't see how I can use the general SQL queries when there are multiple levels of selecting necessary like this.
I could start with something like:
SELECT userID INTO tempUsers
FROM tblUserDepartments
WHERE tblUserDepartments.deptID = MyDeptID
SELECT userName, activityID INTO tempActivities
FROM tblUserInfo
WHERE tblUserInfo.userID = tempUsers.userID
SELECT activityName, plannedCount, actualCount
FROM tblActivityPlan
WHERE tblActivityPlan.activityID = tempActivities.activityID
I'm starting to confuse myself...this isn't right. I am thinking that somehow I should be using JOIN.
Halfway down the post I skipped down to tell you:
Use JOIN
But I see that you are already suspecting as much.
Note, despite wanting to do more I probably won't have much time to tell you more than that.
is this right? I'm not sure what the difference is between what I put in the ON conditional versus the WHERE conditional...would it make a difffernce if i swapped them?
SELECT tblUserInfo.userName, tblActivityPlan.activityName, tblActivityPlan.plannedCount, tblActivityPlan.actualCount
FROM tblUserInfo
INNER JOIN tblUserDepartments
ON tblUserInfo.userID = tblUserDepartments.userID
WHERE tblActivityPlan.activityID = tblUserInfo.activityID
or is it more like this?
SELECT u.UserName AS User,
a.activityName AS Activity,
a.plannedCount AS Planned,
a.actualCount AS Actual
FROM ???
JOIN tblUserDepartments d ON d.deptID = 555
JOIN tblUserInfo u ON u.userID = d.userID
JOIN tblActivityPlan a ON a.activityID = u.activityID
no idea what to be taking it FROM though...