By some googling, reflecting and try&error I created this query:
SELECT sq.movie_id,
sq.movie_title,
sq.number,
sq.movie_year,
coords.loc_country
FROM (SELECT Count(*) AS `number`,
`coords`.`id_movie` AS movie_id,
`movie`.`title` AS movie_title,
`movie`.`year` AS movie_year
-- possibly more info about the movie
FROM `coords`
LEFT JOIN `movie`
ON `movie`.`id` = `coords`.`id_movie`
GROUP BY `coords`.`id_movie`
) AS sq
LEFT JOIN coords ON coords.id_movie = sq.movie_id
ORDER BY sq.number DESC, sq.movie_title ASC
It seems to be fairly complex to me and my question is: Can it be simplified?
The table movie
contains information like year, title, genre etc. As there is more than one location
for each movie, the locations are kept in another table named coords
. The objective of the query above is:
Get the number of locations for each movie and additionally the locations themselves and order the
results by the number.
Update: In order to clarify the objective of this query, this is the result after some post processing:
array(632) {
[881]=>
array(4) {
["movie_title"]=>
string(20) "Eddie Izzard: Circle"
["movie_year"]=>
string(4) "1984"
["number"]=>
string(1) "6"
["drehorte"]=>
array(6) {
[0]=>
string(6) "Brazil"
[1]=>
string(5) "Kenya"
[2]=>
string(7) "Ukraine"
[3]=>
string(4) "Peru"
[4]=>
string(11) "Philippines"
[5]=>
string(8) "Slovenia"
}
}
[171]=>
array(4) {
["movie_title"]=>
string(5) "Torso"
["movie_year"]=>
string(4) "1923"
["number"]=>
string(1) "6"
["drehorte"]=>
array(6) {
[0]=>
string(11) "Philippines"
[1]=>
string(7) "Vietnam"
[2]=>
string(5) "China"
[3]=>
string(5) "Japan"
[4]=>
string(4) "Peru"
[5]=>
string(8) "Colombia"
}
}
[266]=>
array(4) {
["movie_title"]=>
string(24) "Anton Chekhov's The Duel"
["movie_year"]=>
string(4) "1939"
["number"]=>
string(1) "5"
["drehorte"]=>
array(5) {
[0]=>
string(5) "China"
[1]=>
string(6) "Brazil"
[2]=>
string(6) "Russia"
[3]=>
string(14) "Czech Republic"
[4]=>
string(6) "Mexico"
}
}
Some data related to each movie and an array or list of the location (drehorte). Code of the postprocessing:
$result = $pdo->query($sql);
$resultArr = [];
$movieId = -1;
while ($row = $result->fetchObject()) {
if ($row->movie_id != $movieId) {
$movieId = $row->movie_id;
$resultArr[$movieId] = [
'movie_title' => $row->movie_title,
'movie_year' => $row->movie_year,
'number' => $row->number,
'drehorte' => [],
];
}
$resultArr[$movieId]['drehorte'][] = $row->loc_country;
}