简体   繁体   中英

SQL query for object with specific entries on a join table

I have a join table with the following columns:

target_id
assoc_id
int_attr

They represent my target object, its associated object, and an integer attribute that describes the association.

I am given a hash with keys representing the association attribute and values which contain the associated id with that attribute. For example:

{
  1: [3, 5],
  2: [7, 9],
}

I am trying to develop an SQL query which finds all target_ids with the appropriate join table entries. In the example above, it would find any target object with the 4 entries:

`targets_assocs`
target_id assoc_id int_attr
X         3        1
X         5        1
X         7        2
X         9        2
A         3        1
A         5        1
A         7        2
A         9        2
C         2        1
C         4        1
C         6        2
C         8        2

In this case, it would return X and A, ignoring, C.

I was trying to use some type of HAVING clause. I am trying to avoid having multiple nested subqueries using IF EXISTS. Any thoughts or advice would be appreciated.

I really have not written requests for MySQL, sorry for typos.

SELECT `target_id` FROM (
   SELECT `target_id`, count(*) FROM (
      SELECT `targets`.`target_id`, `targets_assocs`.`int_attr` FROM `targets`
       INNER JOIN `targets_assocs` ON `targets_assocs`.`target_id` = `targets`.`id`
       GROUP BY `targets`.`target_id`, `targets_assocs`.`int_attr`
   ) 
   GROUP BY `target_id`
   HAVING COUNT(*) = 2)

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