How to exclude some data on a SQL query depending on it's different values?

user157629 :

I have the following 2 tables:

create table Director (

    id_director int,
    name varchar(255),
    primary key (id_director)
);

create table Movies (

    id_movie int,
    id_director int,
    title varchar(255),
    year int,
    primary key (id_movie),
    foreign key (id_director) references Director (id_director)
);

Some data has been already inserted on this tables. Imagine the data is:

Table Director

id_director       name
-------------------------
   1               Charles
   2               Jack
   3               Katia
   4               David

Table Movies

id_movie      id_director     title        year
------------------------------------------------
   1              2            title1      1999
   2              1            title2      2011
   3              1            title3      2019
   4              3            title4      2019
   5              4            title5      1968
   6              3            title6      2020
   7              2            title7      1977
   8              4            title8      2004
   9              1            title9      2020

I want to execute a SELECT clause in order to filter the directors that it's first movie its from 2019. Note from the example that only the director with the id_director = 3 meets the requirement as has made 2 films, one on 2019 and the other one on 2020.

How can I do this?

The output I would like to get is:

id_director          name
------------------------------
    3                Katia

I have tried this, but it's obviously wrong because some directors that made films before 2019, have also made films after 2019.

select director.id_director, director.name from director, movies
where director.id_director = movie.id_director and year = 2019
group by (name);

I'm using MySQL and I'm supposing I can do this with an IN / NOT IN subquery (but how)?

alex stacey :

If I understand right you want to look at the min(year) for that director. So the SQL would be something like:

select * from movies m
inner join directors d on m.id_director = d.id_director
where min(m.year) = 2019
group by d.id_director;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=11411&siteId=1