我有一个问题表,每个问题都有一个级别,硬度从1到4, 我想得到同一级别的问题行数。
这是我试过的:
$result1 = mysqli_query($con,"SELECT * from questions WHERE level=1");
$result2 = mysqli_query($con,"SELECT * from questions WHERE level=2");
$result3 = mysqli_query($con,"SELECT * from questions WHERE level=3");
$result4 = mysqli_query($con,"SELECT * from questions WHERE level=4");
$n1 = mysqli_num_rows($result1);
$n1 = mysqli_num_rows($result2);
$n1 = mysqli_num_rows($result3);
$n1 = mysqli_num_rows($result4);
好吧,它太糟糕了,并且使用了四个查询来做到这一点
另一种方式是我使用php:
$level = array(0,0,0,0);
$result = mysqli_query($con,"SELECT * from questions");
while($res = mysqli_fetch_array($result)){
switch ($res['level']){
case '1':
$level[0]++;
break;
case '2':
$level[1]++;
break;
case '3':
$level[2]++;
break;
case '4':
$level[3]++;
break;
default:
echo "WTF";
}
}
echo "LEVEL 1 :$level[0]<br>LEVEL 2 :$level[1]<br>LEVEL 3 :$level[2]<br>LEVEL 4 :$level[3]<br>";
这使用php而不是mysql,但看起来更快。有没有其他更快的方法来实现这一目标?什么是最好的方式?
答案 0 :(得分:6)
我认为你只想要一个group by
查询:
SELECT level, count(*)
FROM questions
GROUP BY level;
编辑:
如果使用条件聚合来获取一行数据,可能会更容易:
SELECT SUM(level = 1) as num1, SUM(level = 2) as num2,
SUM(level = 3) as num3, SUM(level = 4) as num4
FROM questions;
这会在一行中生成四个变量,您可以在php中轻松访问。