我有一个数组
$genreQuery = $con ->query ("select distinct(movie_year) from movies");
$movieGenre = array();
$movieTitle = array();
$movieList = array();
while($row = $genreQuery->fetch_object()) {
$movieGenre[] = $row;
}
foreach($movieGenre as $MGenre){
$query = $con ->query
("
select '$MGenre->movie_year' movie_year, IFNULL(count(*)/(select count(*)
from user_movie_ratings where user_id = '$userid'),0) rating
from user_movie_ratings umr,
movies m
where umr.user_id = '$userid'
and umr.movie_id = m.id
and m.movie_year = '$MGenre->movie_year' ORDER BY rating DESC;
");
while($row = $query->fetch_object()) {
$movieTitle[] = $row;
}
}
$text = "";
foreach($movieTitle as $MTitle){
if (empty($text)){
$text = "\"".$MTitle->movie_year."\"";}
else{
$text = $text.",\"".$MTitle->movie_year."\"";
}
}
$list = $con ->query
("
SELECT movie_name, avg_rating, image, id, genre
FROM movies
WHERE id NOT IN (SELECT movie_id FROM user_movie_ratings WHERE user_id = '$userid')
ORDER BY field(movie_year, $text), avg_rating DESC;
");
while($row = $list->fetch_object()) {
$movieList[] = $row;
}
数组由上面的查询填充,我想要做的是按评级排序,看起来像这样
year rating
2014 0.0001
2015 0.0000
2013 0.0000
1967 0.0000
.... ......
.... ......
etc etc
我已经尝试将ORDER BY rating DESC
添加到查询中,但这不起作用,当我使用rsort($movieTitle)
时,它按年份排序而不是评级我需要进行某种多维排序,或者还有另一种方式吗?
答案 0 :(得分:0)
我猜想rating
的排序不起作用,因为您似乎在foreach
循环中运行多个查询,每次迭代都会有一年。因此,在这种情况下,您的订单将按年度进行,然后按年度进行评级。
你应该摆脱那个循环,只做一个查询,然后条件和排序顺序是:
...
AND m.movie_year IN (the,years,you,want)
ORDER BY rating DESC
通过像现在这样循环遍历$movieGenre
,您可以轻松生成逗号分隔列表,以便在IN
语句中使用这些年份。
修改:根据您的评论,您需要所有年份,因此查询中的foreach
循环和年份条件是不必要的。
您可能需要以下内容:
SELECT m.movie_year, IFNULL(count(*)/(select count(*)
from user_movie_ratings where user_id = '$userid'),0) rating
FROM user_movie_ratings umr,
movies m
WHERE umr.user_id = '$userid'
AND umr.movie_id = m.id
ORDER BY rating DESC
当然假设用户ID在查询中使用是安全的,您应该使用预准备语句来避免潜在的SQL注入。
现在,您将所有结果都放在一个查询中,因此不再需要外部循环。