A
A
apptimeru2018-02-02 01:48:39
MySQL
apptimeru, 2018-02-02 01:48:39

How to make a one-to-many query?

Good night gentlemen, I've been struggling with one problem for several hours now, I can't make an adequate request.
There are 2 tables, one main for example with films, the second additional with metadata. Each genre is linked to a movie by a foreign key and has its own row in the meta table.
So the problem is that I can’t display all the films that belong to two or more genres at once, it turns out that if you use IN, then all films that have at least one genre are displayed, and if using AND then an empty result.
Please help me make the right request.
Here is a more illustrative example:
5a73b1e11b102156942086.png
You need to pull out all the names of films that have genres with ID (13,15,27), but not just one, but only those films that have all 3 of these genres.
Request example:

SELECT * FROM films f 
     LEFT OUTER JOIN meta_films m ON m.id_films = f.id 
        WHERE m.meta_value IN(13,23)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Stalker_RED, 2018-02-02
@Stalker_RED

select * from films f
  left join жанры...
  where жанры in(1,2,3)

  group by f.id
  having count ... < -- magic here

after grouping, you can understand which film has one hit, which has two, or more.
https://dev.mysql.com/doc/refman/5.7/en/group-by-f...
www.dofactory.com/sql/having

A
Alexander, 2018-02-02
@SAnhPa

SELECT
    f.*
FROM
    films f
LEFT JOIN meta_films m ON
    m.id_films = f.id
    AND m.meta_value IN(13, 23)
WHERE
  m.id_films IS NOT NULL

D
Dmitry Entelis, 2018-02-02
@DmitriyEntelis

Come on, simple request.

select
  films.*
from meta
left join films on films.id = meta.id_films
where meta_value in (13,15,27)
group by id_films
having count(meta.id) = 3

In IN you substitute all the necessary categories
having count = the total number of categories requested by the user.
If you need a fuzzy search, for example, you can do this:
select
  films.*,
  count(meta.id) as cnt
from meta
left join films on films.id = meta.id_films
where meta_value in (13,15,27)
group by id_films

continue to show the user in descending cnt

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question