开发者

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

PHP mysqli is this the easiest way?

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];
        }
    }


How about doing this in a single query:

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:

$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

using query in foreach is the worst practice I ever seen

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜