mySQL query to find object that is in relation with all objects. No aggregation operation

hopeless_user :

Query to find gadgets that are in relation with all gadgets. Without using any aggregation operation.

CREATE TABLE `gadget`(
 `gadget` VARCHAR(10)
);

CREATE TABLE `relation`(
 `gadget1` VARCHAR(10),
 `relation` boolean,
 `gadget2` VARCHAR(10),
);

The thought with table relation, is that gadget1 has relation with gadget2 if true.

Gordon Linoff :

The following gets the pairs that are NOT related:

select g1.gadget as gadget1, g2.gadget as gadget2
from gadget g1 join
     gadget g2
     on g1.gadget <> g2.gadget left join -- presumably gadgets are not related to themselves       
     relation r
     on r.gadget1 = g1.gadget and r.gadget2 = g2.gadget
 where r.gadget1 is null

Then, you want the gadgets not in this list:

select g.gadget
from gadget g left join
     (select g1.gadget as gadget1, g2.gadget as gadget2
      from gadget g1 join
           gadget g2
           on g1.gadget <> g2.gadget left join
           relation r
           on r.gadget1 = g1.gadget and r.gadget2 = g2.gadget
      where r.gadget1 is null
     ) gg
     on g.gadget = gg.gadget1
where gg.gadget1 not null;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=276762&siteId=1