I have three tables (simplified here):

recipients: recipientId, isGroup
users: userId, first name, last name
groups: groupid, groupname

I want to retreive the first name / last name if the recipient is a user, and the group name if the recipient is a group. It's possible that the recipient is neither (i.e. a group that was deleted/no longer exists), so in that case I want to return nothing.

So this is what I did:

select u.first_name, u.last_name, g.groupname, r.isGroup
from recipients r
left join users u on u.userid = r.recipientId
left join groups g on g.groupid = r.recipientId
where r.isGroup IS NULL or g.groupname IS NOT NULL

The above query is not returning expected results. I am getting this back:

adam, smith, null, null
yolanda, smith, null, null
null, null, members, 1
null, null, null, 1

The last row is unexpected, since clearly there is no group name (g.groupname is NULL) and r.IsGroup = 1.

When I do this:

select u.first_name, u.last_name, g.groupname, r.isGroup
from recipients r
left join users u on u.userid = r.recipientId
left join groups g on g.groupid = r.recipientId
where r.isGroup IS NULL

I get expected results:

adam, smith, null, null
yolanda, smith, null, null

And when I do this:

select u.first_name, u.last_name, g.groupname, r.isGroup
from recipients r
left join users u on u.userid = r.recipientId
left join groups g on g.groupid = r.recipientId
where g.groupname IS NOT NULL

I get expected results:

null, null, members, 1

It's only when I combine the two where clauses with an OR, do I get the additional row.

Now, when I change my query to (change from IS NULL to ISNULL):

select u.first_name, u.last_name, g.groupname, r.isGroup
from recipients r
left join users u on u.userid = r.recipientId
left join groups g on g.groupid = r.recipientId
where r.isGroup IS NULL or ISNULL(g.groupname, null) IS NOT NULL

I get the expected results:

adam, smith, null, null
yolanda, smith, null, null
null, null, members, 1

In fact, I don't even have to change the where clause, the following query works just as well too and gives me the expected result shown above:

select u.first_name, u.last_name, ISNULL(g.groupname,null), r.isGroup
from recipients r
left join users u on u.userid = r.recipientId
left join groups g on g.groupid = r.recipientId
where r.isGroup IS NULL or g.groupname IS NOT NULL

SO, the question is, WHY? Why does putting ISNULL in my SELECT statement change how the WHERE clause works? Why does it make a difference at all? Why does my first query not work? Why is it that it fails to function only when I add the OR - why isn't it broken without it too?

Thanks in advance.

I am using MS SQL Server 2008.

edits: fixed typo, clarified question

没有正确的解决方案

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top