select w.id, w.name, m.id, m.name, count(c.id) connections
from widgets w
join connections c
on c.widget_id = w.id
join modes_connections mc
on mc.connection_id = c.id
join modes m
on m.id = mc.mode_id
group by w.id, w.name, m.id, m.name
;
id
name
id
name
connections
1
widget1
1
A
2
1
widget1
2
B
2
1
widget1
3
C
2
1
widget1
4
D
2
…
hidden batch(es)
;with x as
(
select w.id, w.name, m.id mode_id, m.name mode_name, count(c.id) connections
from widgets w
join connections c
on c.widget_id = w.id
join modes_connections mc
on mc.connection_id = c.id
join modes m
on m.id = mc.mode_id
group by w.id, w.name, m.id, m.name
)
select id, name
from widgets wdg
where exists (select 1 from x where id=wdg.id and mode_id = 1 and connections = 2)
and exists (select 1 from x where id=wdg.id and mode_id = 2 and connections = 2)