简体   繁体   English

PHP mysqli是最简单的方法吗?

[英]PHP mysqli is this the easiest way?

The code snippet is meant to return the minimum and maximum id from each round in this table 该代码段旨在返回此表中每一轮的最小和最大id I'm just wondering if there is a less clunky way of doing this. 我只是想知道是否有一种不太笨拙的方法。

$query = "SELECT round FROM $tablename";
$rounds = Array();
if ($result = $Login->mysqli->query($query)) {
    while ($row = $result->fetch_array(MYSQL_ASSOC)) {
        $rounds[] = $row['round'];
    }
}
$rounds = array_unique($rounds);
$rounds = array_values($rounds);
$roundBound = Array();
foreach ($rounds as $roundNum) {
    $query = "SELECT MIN(id), MAX(id) FROM $tablename WHERE round = $roundNum;";
    $result = $Login->mysqli->query($query);
    $row = $result->fetch_row();
    $roundBound[] = $row[0];
    $roundBound[] = $row[1];
}

hurr... ......

Changed to, 变成,

$query = "SELECT MIN(id), MAX(id) FROM $tablename GROUP BY round";
    if($result = $Login->mysqli->query($query)) {
        while ($row = $result->fetch_row()) {
            $roundBound[] = $row[0];
            $roundBound[] = $row[1];
        }
    }

如何在单个查询中执行此操作:

SELECT MIN(id), MAX(id) FROM $tablename GROUP BY round

It'd be more efficient to run a single query and use a WHERE round IN (....) clause: 运行单个查询并使用WHERE round IN (....)子句会更有效:

$round_clause = implode(',', $rounds);

$query = "SELECT round, MIN(id), MAX(id) FROM $tablename WHERE round IN ($round_clause) GROUP BY round";

As a general rule, doing a single query that returns a "large" number of rows is going to be more efficient than doing a series of smaller/single queries that only return few or one rows at a time. 通常,执行单个查询以返回“大量”行将比执行一系列较小/单个查询(一次仅返回数行或一行)的效率更高。 You only scan the indexes once, you only have to retrieve the data once. 您只需扫描一次索引,只需检索一次数据。

use group by 使用group by

using query in foreach is the worst practice I ever seen 在foreach中使用查询是我见过的最糟糕的做法

SELECT Min(id), Max(id) FROM $tablename GROUP BY round

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

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