简体   繁体   中英

Is there a simpler way to perform this query

Here is that query (MySQL syntax):

select
  id_image
from
  (
    select
        id_image
      , count(id_image) as nb
    from
      data
    group by
      id_image
  ) temp_table
where
  nb = (select count(distinct id_group) from data)
  • data is a table of 3 columns: int id_user, int id_group and int id_image
  • A row (x, y, z) means that:
    • image z is in image group y
    • group y was created by user x

And we want to list all the images that are present in each image group. Thanks.

You are selecting all Image IDs that occur in data as often as there are distinct group IDs in that table? That seems strange.

Anyhow, the query can be re-written as:

select id_image
from data 
group by id_image
having count(*) = (select count(distinct id_group) from data);

How about try this:

select id_group, id_image from data where id_group in (select distinct id_group from data);

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