mysql查询速度的差异


Diffrence in mysql query speeds

假设我的数据库中有1kk条记录。

现在我需要选择一些数据,还需要知道我选择了多少字段,所以我的问题是:

运行一个查询来计算这样的数据更好吗:

SELECT COUNT("id") from table where something = 'something'

在那之后,再运行一个这样的选择查询:

SELECT 'some_field' from table where something = 'something';

或者也许最好只选择数据,然后用php计算,比如:

count($rows);

或者,也许还有更好的方法可以做到这一点,例如,在一个查询中完成所有操作?

字里行间,我想你可能想要的是SQL_CALC_FOUND_ROWS。这允许您选择结果集的一部分(使用LIMIT子句),并且仍然可以在单个操作中计算匹配行的总数。您仍然使用两个查询,但数据中的实际搜索操作只发生一次:

// First get the results you want...
$result = mysql_query("
  SELECT SQL_CALC_FOUND_ROWS
  FROM `table`
  WHERE `something` = 'something'
  LIMIT 0, 10
");
// ...now get the total number of results
$numRows = mysql_query("
  SELECT FOUND_ROWS()
");
$numRows = mysql_fetch_row($numRows);
$numRows = $numRows[0];

如果你提取了所有1000条记录,那么你可以在提取时计数:

$res=mysql_query("SELECT 'some_field' from table where something = 'something'");
while($r = mysql_fetch_*($res)) {
  $count++;
 //> Do stuff
} 

这样,您只进行一个查询,而不使用mysql_num_rows();

一个查询是:

SELECT Count(*) AS NumRows, some_field from table 
GROUP BY some_field where something = 'something';