Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select occurrences that doesn't have a certain value in field

Tags:

sql

mysql

Given a table with fields A and B:

| A | B |
---------
| 1 | p |
| 1 | f |
| 1 | t |
| 2 | p |
| 2 | f |

I am trying to construct a query finding all the A's that doesn't also have a 't' for B somewhere.

So for this data the output should just be

| A |
-----
| 2 |

as 2 doesn't have 't' listed anywhere in field B

I tried doing SELECT DISTINCT A FROM table WHERE B!='t', but that logic is flawed as 1 also contains a row with B!='t'. I also tried various variations of GROUP BY, but I am stuck.

Please help

like image 872
Emil Bonne Kristiansen Avatar asked Jan 05 '23 03:01

Emil Bonne Kristiansen


2 Answers

I would use group by and having for this:

select a
from t
group by a
having sum(b = 't') = 0;
like image 161
Gordon Linoff Avatar answered Jan 08 '23 06:01

Gordon Linoff


Try this:

SELECT A
FROM mytable
GROUP BY A
HAVING SUM(B = 't') = 0

The HAVING clause filters out A groups that contain at least one record with B = 't'.

like image 25
Giorgos Betsos Avatar answered Jan 08 '23 05:01

Giorgos Betsos