Php 更快的mysql查询

Php 更快的mysql查询,php,mysql,Php,Mysql,有没有更快的方法 $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='$typ

有没有更快的方法

$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;

干杯

看看你的查询,我想你在寻找这样的东西:

SELECT SUM(type) / COUNT(*) FROM table1 WHERE ...

通常:
SELECT*
可以“缩短”为,例如
SELECT COUNT(*)
,前提是您只关心匹配行的数量

 SELECT COUNT(*) AS num_results, SUM(type) AS total_type FROM table1
    WHERE id = $id and type = $type
这个查询将生成一个包含两个所需值的单行结果集

请注意,应该使用参数化查询而不是直接变量替换来避免SQL注入攻击

另外,我猜SUM(type)不是您真正想要做的,因为您可以将其计算为(num_results*$type),而无需第二次查询。

一行:

$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;
echo number_format(mysql_result(mysql_query("SELECT SUM(type) / COUNT(*) FROM table1 WHRE id = $id AND type = '$type'"), 0), 2, ',', ' ');

COUNT(*)
稍微好一点(因为它不依赖于字段数据,就像
COUNT(id)
一样)那么无法加入这两个查询?这就是我想要的。谢谢,你能指定参数化查询问题吗?例如,如果$type字段来自用户输入,而用户要键入“13;从用户中删除”在这个领域,你可以看到会发生什么。通过使用参数指定查询(类似于WHERE ID=@ID和type=@type,但这取决于您的数据库库),然后将正确类型的值绑定到参数,您可以安全地抵御此类攻击。他将收到一个错误,但不会删除任何内容。mysql\u query()不会执行多个查询。@丹:显然,我不是php专家。mysql\u查询是否可以注入?您仍然可以恶意地更改查询(将$type设置为“something OR 1=1”),只是无法注入第二个查询来运行。