【问题标题】:Return list of member_number count in table返回表中 member_number 计数列表
【发布时间】:2015-06-26 12:13:17
【问题描述】:

考虑下表

我需要按降序返回一个列表,其中包含在表where tournament = 'EPL' AND ROUND = '12' 中出现频率最高的member_nr的计数

示例

脚本应返回以下结果:

我考虑过这个问题,我的逻辑是这样写的

第 1 步:逐个获取 member_nr

 $sql = "SELECT DISTINCT * 
        FROM winners 
        WHERE tournament='$tour' AND round='$round'";
LOOP(){ //get 1 member number
$mem_nr = ['mem_nr']; //assign mem_nr to variable

STEP2:获取计数(次数)^ABOVE^成员编号出现在表格中

  "$sql="SELECT *, count(member_nr) as nrWins 
   FROM winners 
   where member_nr ='$memNr' and tournament='$tournament' AND     round='$round'";"
 LOOP(){//get count

第 3 步:显示数据

echo $row=['nrWins'] //Display Number Wins
echo $memNr
   }//END LOOP
 }//END LOOP

我的问题:

以上对我来说似乎不是很有效,我正在寻找最短最有效的方法来返回上表中的成员数,欢迎任何想法/建议

【问题讨论】:

标签: php mysql sql


【解决方案1】:

试试这样的:

SELECT *, COUNT(*) AS `wins`
FROM `winners`
WHERE `tournament` = '$tournament'
  AND `round` = '$round'
GROUP BY `member_nr`
ORDER BY `wins` DESC

【讨论】:

  • 我不记得 COUNT 是在 GROUP BY 之前还是之后应用的,但请试一试。
  • 感谢您并给您反馈
  • 您缺少ORDER BY 以按计数降序获取结果。你应该使用count(*) 而不是count(member_nr)stackoverflow.com/questions/2876909/…
【解决方案2】:
select tournament,round,member_nr,count(*)
from table
where tournament = 'EPL'
and round = 12
group by tournament,round,member_nr
order by count(*) desc

【讨论】:

  • 当您只使用WHERE 子句选择其中一个时,为什么要将roundtournament 放在GROUP BY 中?
  • 习惯的力量.. 大多数 SQL 实现要求所有非聚合列都包含在 group by 中。虽然我认为 MySQL 是这条规则的一个例外,但它们并不是真正需要的。
  • SELECT 中也不需要它们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-11
  • 1970-01-01
  • 2021-07-03
  • 2020-10-04
  • 1970-01-01
  • 1970-01-01
  • 2020-08-12
相关资源
最近更新 更多