T
T
tytar2017-01-23 17:27:38
MySQL
tytar, 2017-01-23 17:27:38

How to select all records from table a which have the entire list matched from table b?

Good afternoon!
There are two tables a and b and there are many to many between them
how to select all records from table a which have full set of records from b e.g. ['foo', 'bar', 'baz'], records a which only have foo or bar weed out

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton, 2017-01-23
@MoonMaster

Maybe Instersect can help you

R
Rsa97, 2017-01-23
@Rsa97

SELECT `a`.*
  FROM `a`
  JOIN (
    SELECT `a_id`, COUNT(*) AS `count_ab`
      FROM `a_to_b`
      GROUP BY `a_id`
  ) AS `x` ON `x`.`a_id` = `a`.`id`
  JOIN (
    SELECT COUNT(*) AS `count_b`
      FROM `b`
  ) AS `b` ON `b`.`count_b` = `x`.`count_ab`

It will work if the records in the link table are unique, that is, there are no duplicate pairs (`a_id`, `b_id`)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question