How can I filter information ordering by two different factors on SQL?

user157629 :

I have the three following tables:

create table Person (

    id int,
    popularity int,
    primary key (id)
);

create table Movie (

    id int,
    year int,
    primary key (id)
);

create table Person_Movie (

    id_person int,
    id_movie int,
    primary key (id_person, id_movie),
    foreign key (id_person) references Person (id_person),
    foreign key (id_movie) references Movie (id_movie)
);

I want to execute a SELECT to check which person has the higher number of popularity BUT has but has participated in less movies.

How can I do this?

To check the most popular person I'd execute this:

select P.id from Person as P, Movie as M, Person_Movie as PM
where P.id = PM.id and PM.id = M.id
group by (P.id)
order by popularity;

And, if I am correct, to check the person that has participated in less movies I'd execute this:

select P.id from Person as P, Movie as M, Person_Movie as PM
where P.id = PM.id and PM.id = M.id
group by (P.id)
order by count(M.id);

But, how can I filter the two cases in one SELECT?

Thanks in advance.

EDIT

I'm using MySQL.

Also I'll provide an example of what I'm trying to get:

Table Person

id      popularity
-------------------
1          50
2          35
3          120
4          45

Table Movie

id        year
----------------
1         1999
2         2014
3         1969
4         1977
5         2019

Table Person_Movie

id_person       id_movie
--------------------------
    1              1
    2              4
    2              5
    3              3
    4              1
    4              2

So, given this example, the output I would like to get is:

id_person
----------
    3

Because both persons with id 1 and 3 have participated in just ONE movie, but person with id 3 has the higher number of popularity.

CR7SMS :

How about this:

select P.id from Person as P, Movie as M, Person_Movie as PM
where P.id = PM.id and PM.id = M.id
group by (P.id)
order by max(popularity),count(M.id);

This would sort your results by the count of movies if multiple people have the same popularity. If you want only the first row, you can use a top 1. Hope this helps.

Edit:

Based on the sample cases, it looks like the first priority of sorting should go to count:

select P.id from Person as P, Movie as M, Person_Movie as PM
where P.id = PM.id and PM.id = M.id
group by (P.id)
order by count(M.id),max(Popularity) desc;

Guess you like

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