简体   繁体   中英

How do I select a column's values only if the values exist in another column in SQL?

I have a slightly complicated question. There are a few columns. Essentially the logic is that there are a bunch of titles. Each title has a unique identifier and these are part of a series. As evident in 'Table Now' there are a few different Goblins: Goblins, Goblins 2 and Goblins 3. These have separate unique identifiers if they are different titles but since they are all Goblins they have a unique series identifier. These titles/creatures can have any home. But Sauron only owns those in Lairs.

What I would like to figure out is the % of what Sauron owns is unique to Sauron versus something else owned by another person. So for example, Vampires is uniquely owned by Sauron as no one else owns it. If a unique series identifier is owned by Sauron then I want it.

The way I have thought about to tackle this is to find all that Sauron owns. Based on the unique series identifier of what Sauron owns I would like to find everything in the table. At the moment there are very few unique series identifier so it is easy to type it manually like unique series identifier = 'Gob' but if there were many many, how would I go about this? I want to find all that Sauron owns and all matches of the unique series identifier where Sauron owns too. So stuff like Monsters and Trolls not being owned by Sauron are not present. And imagining that this table is a million or more rather than a small set of things.

Appreciate any help and sorry for the wordvomit, couldn't think of a better way to explain this! :D

Example table to showcase

You want "title"s that have at least one "Sauron". If so, you can use window functions:

select t.*
from (select t.*,
             sum(case when evillord = 'Sauron' then 1 else 0 end) over (partition by title) as num_saurons
      from t
     ) t
where num_saurons > 0;

Select all unique series identifiers for Sauron. Then select all titles with those unique series identifiers.

select * from mytable 
where unique_series_identifier in 
(
  select unique_series_identifier
  from mytable
  where evil_lord = 'Sauron'
)
order by unique_series_identifier, unique_identifier;

I suggest to have the following indexes for this query. One to find Saurons titles, one to find titles by unique series identifier.

create index idx1 on mytable ( evil_lord, unique_series_identifier );
create index idx2 on mytable ( unique_series_identifier );

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