[英]How can I order by count in mysql when the count need data to calculate from this select statement?
看我的代码,在我从该选择语句中获取数据后,我希望按计数百分比选择一条语句,这显然是不合逻辑的。 我能做什么? 帮助,感激不尽。
<?php //myslq connection code, remove it because it's not relate to this question $stm =$db->prepare("SELECT id ,term_count, COUNT(user_id) as count FROM sign WHERE term IN (:term_0,:term_1) GROUP BY user_id ORDER by count DESC"); //trying replace order by count with $combine_count, but it's wrong $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']; $term_count_number=$rows['term_count']; $count_percentage=round(($count/$count_user_diff)*100); $count_key_match=round(($count/$term_count_number)*100); $combine_count=round(($count_percentage+$count_key_match)/2); //issue is here, I want the select statement order by $combine_count } ?>
SELECT id ,term_count, COUNT(user_id) as `count`
FROM sign
WHERE term IN (:term_0,:term_1)
GROUP BY user_id
ORDER by `count` DESC");
由于“计数”是一个函数,因此最好在非函数“计数”周围添加后缀,如上所述。
GROUP BY应该列出未聚合的字段。 否则,它不知道要获取哪个id和term_count。 因此,根据您的需求,
要么做
SELECT user_id, COUNT(*) as `count` -- I changed this line
FROM sign
WHERE term IN (:term_0,:term_1)
GROUP BY user_id
ORDER by `count` DESC");
或做
SELECT id ,term_count, COUNT(*) as `count`
FROM sign
WHERE term IN (:term_0,:term_1)
GROUP BY id ,term_count -- I changed this line
ORDER by `count` DESC");
SQL语法逻辑
SELECT column1, count(column1) AS amount
FROM table_name
GROUP BY column1
ORDER BY amount DESC
LIMIT 12
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.