Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select where a and next is c, skipping b

I am wondering if it is possible in SQL to return a single row to show, using the table below as an example, only a row for id 2:

table1  ( id 2 and 4 are missing value b)
id      value
1         a
1         b
1         c
1         d
2         a
2         c
2         d 
3         a
3         b
3         c
3         d
4         a
4         c
4         d

i basically want to find all instances where 'b' does not exist but 'a' still does exist for any id and return a single row for that any given id. i have tried something like this, but its not working as i would want it to:

select * from table1 
    where not exists (select distinct value from table1 where value b)   

i would like the end result to be something this, identifying the values where 'b' does not exist but 'a' does(not showing the value, is unneeded for final goal):

result table
id        
2           
4          
like image 217
wondergoat77 Avatar asked Feb 18 '23 13:02

wondergoat77


2 Answers

SELECT id
FROM table1 t1
WHERE 
    value = 'a'
    AND NOT EXISTS (
        SELECT *
        FROM table1 sub
        WHERE sub.id = t1.id AND sub.value = 'b'
    )
like image 127
Michael Fredrickson Avatar answered Feb 25 '23 10:02

Michael Fredrickson


This should do the job:

select distinct id
from table1 t
where not exists (
    select 1 
    from table1 tt 
    where t.id = tt.id and tt.vallue = 'b'
)  
and exists (
    select 1
    from table1 tt 
    where t.id = tt.id and tt.vallue = 'a'
)

Below you have shorter form. It may perform better and distinct keyword may be unnecessary if the pair (id, value) is unique.

select distinct id
from table1 t
left join table1 tt
on t.id = tt.id and tt.value = 'b'
where t.value = 'a' 
and tt.id is null
like image 40
pkmiec Avatar answered Feb 25 '23 12:02

pkmiec