有更快的方法吗?
$data1 = mysql_query(
"SELECT * FROM table1 WHERE id='$id' AND type='$type'"
) or die(mysql_error());
$num_results = mysql_num_rows($data1);
$data2 = mysql_query(
"SELECT sum(type) as total_type FROM table1 WHERE id='$id' AND type='$type'"
) or die(mysql_error());
while($info = mysql_fetch_array( $data2 )){
$count = $info['total_type'];
}
$total = number_format(($count/$num_results), 2, ',', ' ');
echo $total;
干杯!
答案 0 :(得分:1)
查看您的查询,我认为您正在寻找类似的内容:
SELECT SUM(type) / COUNT(*) FROM table1 WHERE ...
答案 1 :(得分:0)
一般情况下:SELECT *
可以“缩短”为例如SELECT COUNT(*)
,如果你关心的只是匹配的行数。
答案 2 :(得分:0)
SELECT COUNT(*) AS num_results, SUM(type) AS total_type FROM table1
WHERE id = $id and type = $type
此单个查询将生成包含所需值的单行结果集。
请注意,您应该使用参数化查询而不是直接变量替换来避免SQL注入攻击。
另外,我猜测SUM(类型)不是你真正想做的,因为你可以在没有第二个查询的情况下将其计算为(num_results * $ type)。
答案 3 :(得分:0)
$data1 = mysql_query("SELECT sum(type) as total_type,count(*) as num_rows FROM table1 WHERE id='$id' AND type='$type'"
) or die(mysql_error());
$info = mysql_fetch_array( $data1 );
$count = $info['total_type'];
$num_results = $info['num_rows'];
$total = ($count/$num_results);
echo $total;
答案 4 :(得分:0)
一行:
echo number_format(mysql_result(mysql_query("SELECT SUM(type) / COUNT(*) FROM table1 WHRE id = $id AND type = '$type'"), 0), 2, ',', ' ');