Here's my table structure:
users
--userid
--firstname
--lastname
users_task
--userid
--taskid
I'd like to show each user once and the id's for a specific assignment. The results should look something like this:
FirstName | LastName | Users_Task.UserID | TaskID
John Doe Null Null
Suzy Doe 101 39
I've made a query that works but if I specify task 38 then Suzy Doe does not s开发者_运维技巧how up in the results because she is not null or 38. I need each user to show up once, every time.
Here's my actual SQL. Sorry about the vb variable in the WHERE statement:
SELECT users.userid AS UserUserID, users.firstname AS UserFirstName,
users.lastname AS UserLastName,
issue_assigneduser.issueid as AssignedIssueID,
issue_assigneduser.userid as AssignedUserID
FROM users LEFT OUTER JOIN
issue_assigneduser ON users.userid = issue_assigneduser.userid
WHERE (users.disabledyn = 0 AND (issueid Is Null or issueid = " & iIssueID & "))
ORDER BY UserFirstName, UserLastName
I'm using SQL Server 2008 but I'm assuming and hoping that the solution will be fairly generic.
Put your issueid in the join, not there where
SELECT users.userid AS UserUserID, users.firstname AS UserFirstName,
users.lastname AS UserLastName,
issue_assigneduser.issueid as AssignedIssueID,
issue_assigneduser.userid as AssignedUserID
FROM users LEFT OUTER JOIN
issue_assigneduser ON users.userid = issue_assigneduser.userid
AND (issueid Is Null or issueid = " & iIssueID & ")
WHERE users.disabledyn = 0
ORDER BY UserFirstName, UserLastName
At this point, you can probably even get away with
SELECT users.userid AS UserUserID, users.firstname AS UserFirstName,
users.lastname AS UserLastName,
issue_assigneduser.issueid as AssignedIssueID,
issue_assigneduser.userid as AssignedUserID
FROM users LEFT OUTER JOIN
issue_assigneduser ON users.userid = issue_assigneduser.userid
AND issueid = " & iIssueID & "
WHERE users.disabledyn = 0
ORDER BY UserFirstName, UserLastName
Try this:
SELECT users.userid AS UserUserID, users.firstname AS UserFirstName,
users.lastname AS UserLastName,
issue_assigneduser.issueid as AssignedIssueID,
issue_assigneduser.userid as AssignedUserID
FROM users LEFT OUTER JOIN
issue_assigneduser
ON users.userid = issue_assigneduser.userid
AND (issueid Is Null or issueid = " & iIssueID & ")
WHERE (users.disabledyn = 0)
ORDER BY UserFirstName, UserLastName
Including the criteria in the WHERE clause forced an INNER JOIN, even though you specified LEFT.
精彩评论