简体   繁体   English

更快的mysql查询

[英]faster mysql query

Is there a faster way to do this? 有更快的方法吗?

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

Cheers! 干杯!

查看您的查询,我认为您正在寻找这样的东西:

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

This single query will produce a one-row result set with both values that you want. 该单个查询将生成一个包含两个所需值的单行结果集。

Note that you should use a parameterized query instead of direct variable substitution to avoid SQL injection attacks. 请注意,应使用参数化查询而不是直接变量替换,以避免SQL注入攻击。

Also, I'm guessing that SUM(type) isn't what you really want to do, since you could calculate it as (num_results * $type) without the second query. 另外,我猜想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, ',', ' ');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM