在同一查询中,MySql可以计数行并仅获得第一行?

时间:2018-08-27 14:07:59

标签: php mysql database performance mysqli

在同一查询中,MySql可以计算行并仅获得第一行?

现在我使用此代码(而且我不知道是否正确):

$query1 = "
SELECT  magni
    FROM  earthquakes
    WHERE  (milli BETWEEN '$data_dal' AND '$data_al')
      AND  (magni BETWEEN '$magn_min' AND '$magn_max')
      AND  (ipoc BETWEEN '$ipo_min' AND '$ipo_max')
      AND  (lati BETWEEN '$lat_inf' AND '$lat_sup')
      AND  (longi BETWEEN '$lng_sin' AND '$lng_des')
    ORDER BY  magni DESC
    LIMIT  1";
$query2 = "
SELECT  COUNT(*)
    FROM  earthquakes
    WHERE  (milli BETWEEN '$data_dal' AND '$data_al')
      AND  (magni BETWEEN '$magn_min' AND '$magn_max')
      AND  (ipoc BETWEEN '$ipo_min' AND '$ipo_max')
      AND  (lati BETWEEN '$lat_inf' AND '$lat_sup')
      AND  ((longi BETWEEN '$lng_sin' AND 180)
              OR  (longi BETWEEN -180 AND '$lng_des')
           )";

$result1 = mysqli_query($con,$query1);
$result2 = mysqli_query($con,$query2);
$array_statistiche = array($result2,$result1);  //numero eventi sismici, magniudo più alta

mysqli_free_result($array_statistiche);
$array_finale= $array_statistiche;

$array_terremoti= json_encode($array_finale); // return value of numero terremoti e array terremoti
mysqli_close($con); // close connection with database

非常感谢,我的英语很抱歉!

2 个答案:

答案 0 :(得分:2)

在低于8+的MySQL版本中,您需要两个单独的查询来执行此操作。但是,您始终可以将子查询添加到您的限制查询的select子句中,以找到总数,如下所示:

SELECT
    magni,
    (SELECT COUNT(*) FROM earthquakes WHERE ...) AS cnt
FROM earthquakes
WHERE ...
ORDER BY magni DESC
LIMIT 1

我省略了一些代码,部分原因是它不会影响答案,部分原因是我不精通如何用PHP编写好的语句。您应该阅读有关PHP中准备好的语句的信息,因为通常不建议将变量直接插入查询字符串中。

如果您感到好奇,可以使用COUNT作为分析函数,在不使用任何子查询的情况下,在MySQL 8+中使用上述语句:

SELECT
    magni,
    COUNT(*) OVER () AS cnt
FROM earthquakes
WHERE ...
ORDER BY magni DESC
LIMIT 1

这是一个演示(在SQL Server中,在撰写此答案时最接近的匹配项),展示了该替代方法的作用。

Demo

答案 1 :(得分:1)

如果您要询问笨重的Dumplings were rubbish. 中的重复工作,那么显然是赢家:

WHERE

第一个获取您的SELECT SQL_CALC_FOUND_ROWS magni FROM earthquakes WHERE ... ORDER BY magni DESC LIMIT 1; SELECT FOUND_ROWS(); ,然后继续扫描表以获取计数。第二个以线程安全的方式获取计数。

magni获得所需的单个值而没有SELECT MAX(magni) ...。但这在这种情况下无济于事。

这些索引可能有助于加快速度。仅使用一个,但优化程序将选择其中一个。

ORDER BY

如果您真的只需要执行一个返回两个结果的查询,请考虑:

INDEX(magni),
INDEX(milli),
INDEX(lati)

也就是说,将两个大查询都埋在一个SELECT ( SELECT MAX(magni) ... ) AS max_magni, ( SELECT COUNT(*) ... ) AS ct; 中。您将重复SELECT并执行两次相同的扫描。