0

So I have the following data in a table.

ID        Name        fID        mID
1         Bob         135        100
2         James       Null       100
3         Graham      Null       100
4         Gemma       142        100

What I want to do is return Bob, James, Graham, based on the fact that they are all under the mID of 100, but also that the fID is 135 or NULL. This excludes Gemma, since while she is under 100, she has an fID of 142 which is not 135 or NULL.

So far I have tried doing this:

SELECT ID, Name
FROM table1
WHERE mID=100 AND fID IN (SELECT fID FROM table1 WHERE fID=135 AND fID IS NULL)

But that returns nothing. Any suggestions helpful.

2 Answers 2

2
SELECT ID, Name
FROM table1
WHERE mID=100 AND (fID = 135 OR fID is NULL)
Sign up to request clarification or add additional context in comments.

Comments

0

In your subselect, you should use OR instead of AND.

SELECT ID, Name FROM table1
WHERE mID=100 AND fID IN (SELECT fID FROM table1 WHERE fID=135 OR fID IS NULL)

is wrong, here the correct one:

select id, name from table1 where mid = 100 and id in 
(SELECT ID FROM table1 WHERE fID=135 OR fID IS NULL)

6 Comments

That wouldn't work. If fID is NULL, fID IN (whatever) will never be true.
here ist the corrected way: select id, name from table1 where mid = 100 and id in (SELECT ID FROM table1 WHERE fID=135 OR fID IS NULL)
That would work. It would be needlessly complicated, in my opinion, but it is valid nonetheless. You can edit your answer to say that, and if you do, I'll be happy to retract my downvote.
depending on the SQL dialect (was not told by op), there are better ways, Oracle: NVL, mssql Isnull ....
The OP did: it's Microsoft SQL Server. You can tell from the tags. I think you're thinking of ISNULL(fID, 135) = 135, which again is valid, but more complicated than Andrei Hirsu's answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.