简体   繁体   中英

Oracle query self-join?

I've simplified this example but hopefully the example provides enough substance to make sense.

If I have a table such as the following...

ITEM GROUP
---- ----- 
 A     1
 B     1
 C     1
 D     2
 E     2
 F     3
 G     4

... and I am provided items A, B, D and F, I would like to contruct a query that will return those details along with the additional items in the associated groups, C and E.

It seems that I should be able to do some sort of inner join but I'm not clear on how it could be done. It would be best if this were done in a single query due to the constraints of the environment.

Thanks much!

If I understand you correctly, this would work.

SELECT item,
       group_num
  FROM table_name
 WHERE grroup_num IN (SELECT group_num
                        FROM table_name
                       WHERE item IN ('A', 'B', 'D', 'F'))

You could also write it as an EXISTS

SELECT item,
       group_num
  FROM table_name a
 WHERE EXISTS( SELECT 1
                 FROM table_name b
                WHERE a.group_num = b.group_num
                  AND b.item IN ('A','B','D','F') )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM