在这种情况下,我可以用什么方式根据mysql语句中的计算值对数据进行排序


In what way can I order data by the calculated value in my mysql statement in this situation?

我希望mysql select语句按$combine_count排序,但$combine_count是根据该语句计算的。你有办法实现我的目标吗?学徒。

$stm =$db->prepare("SELECT id , COUNT(user_id) as 'count'FROM sign   WHERE term IN (:term_0,:term_10)");
	$term_0="$term[0]";
	$term_1="$term[1]";
	
	$stm->bindParam(":term_0", $term_0);
	$stm->bindParam(":term_1", $term_1);
	$stm->execute();
$rows = $stm->fetchALL(PDO::FETCH_ASSOC);
foreach ($rows as $rows) {
    $count=$rows['count'];
  
	$count_percentage=round(($count/$count_user_diff)*100);
	$count_key_match=round(($count/$term_match_number)*100);
	$combine_count=round(($count_percentage+$count_key_match)/2);	
	
	echo $combine_count ;	
			 	
}//foreach

您的代码没有显示$term_match_number$count_user_diff来自哪里,但肯定不是来自SQL。所以,不,在这种特殊情况下你不能这样做。

最好的方法不是直接回显,而是在PHP端对数组进行排序。

$array = array();
foreach ($rows as $rows) {
    $count=$rows['count'];
    $count_percentage=round(($count/$count_user_diff)*100);
    $count_key_match=round(($count/$term_match_number)*100);
    $combine_count=round(($count_percentage+$count_key_match)/2);   
    $array[] = $combine_count ; 
}
sort($array); // sorts ascending (low to high)
rsort($array); // sorts descending (high to low)

我不确定MySQL是否能处理它,但值得一试:

SELECT s.id, s.count
FROM (SELECT id, COUNT(user_id) as 'count' FROM sign WHERE term IN (:term_0,:term_10) GROUP BY id) AS s
ORDER BY s.count