为什么在使用SQL AVG()函数时mysqli_num_rows总是返回1?

时间:2018-12-15 13:06:15

标签: php mysql

我正在开发一种投票系统,并且遇到SELECT AVG函数和mysqli_num_rows之间的不兼容问题。

使用AVG()时,mysqli_num_rows总是返回数字1。但是,我的if语句需要实际的行数。我该怎么办?

$consulta_nota_geral = "SELECT * , avg(comp1) as competencia1 , avg(comp2) as competencia2 , avg(comp3) as competencia3 , avg(comp4) as competencia4 , avg(comp5) as competencia5  FROM votos WHERE topic_id = '$topic_id'";
$consulta_nota_geral_conect = mysqli_query($conn,$consulta_nota_geral) or die (mysqli_error($conn));

if(mysqli_num_rows($consulta_nota_geral_conect) > 0) {
    //other code here
}

2 个答案:

答案 0 :(得分:0)

SQL返回一行,因为它正在使用聚合函数(avg)。如果将import requests, json, re html = requests.get('https://.......').text jsonStr = re.search(r'window.pageData=(.*?)</script>', html).group(1) jsonObject = json.loads(jsonStr) for item in jsonObject['mods']['listItems']: print(item['name']) print(item['price']) 添加到选择中,它将返回带有SQL结果的结果。

答案 1 :(得分:0)

我认为由于不兼容,您的意思是mysqli_num_rows()返回1。这是因为AVG()将行分组为一,然后计算平均值。

如果要获取实际的行数,可以使用COUNT(*)

因此,您的查询将是:

SELECT COUNT(*) as number_of_rows, avg(comp1) as competencia1 , avg(comp2) as competencia2 , avg(comp3) as competencia3 , avg(comp4) as competencia4 , avg(comp5) as competencia5  FROM votos WHERE topic_id = '$topic_id'

然后,您将使用mysqli_fetch_row()mysqli_fetch_assoc()来获取数据。

$consulta_nota_geral = "SELECT COUNT(*) as number_of_rows, avg(comp1) as competencia1 , avg(comp2) as competencia2 , avg(comp3) as competencia3 , avg(comp4) as competencia4 , avg(comp5) as competencia5  FROM votos WHERE topic_id = '$topic_id'";
$consulta_nota_geral_conect = mysqli_query($conn,$consulta_nota_geral) or die (mysqli_error($conn));

$data = mysqli_fetch_assoc($consulta_nota_geral_conect);
if($data["number_of_rows"] > 0) {
    //your code
}