2

This is a very basic query (related to this one) I can't figure out …

Let's say I have a two column table like this:

A  -  B
1  -  1
1  -  2
1  -  3
2  -  1
3  -  1
3  -  4

I want to get all distinct As that do not have a B of 2 or 3. Using the above example, the only results I want returned is As 2 and 3. How do I do this?

2 Answers 2

4
SELECT DISTINCT `A` FROM `t` AS `t1`
    WHERE NOT EXISTS (
        SELECT 1 FROM `t` 
            WHERE `t`.`A` = `t1`.`A` 
            AND `B` in (2,3)
    );

SQL Fiddle demo

Sign up to request clarification or add additional context in comments.

6 Comments

You can achieve the same results without the complexity. See LD answer.
+1 correct (but aweful formatting). I have no idea why someone downvoted it.
@aldux: It is just I want to get all distinct As that do not have a B of 2 or 3 translated into SQL :)
Maybe i don't get it,but distinct A where B is not 2 or 3 wont return 1,2,3?
@Mihai: NOT "A where B..." but "As that do not have a B...". It makes difference. For A=1 THERE are B=2 and 3.
|
0

try to use the following code:

select distinct a
from tbl
where B not IN(2,3)

1 Comment

This would still return 1 for A because in the first row of A B is neither 2 nor 3 …

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.