简体   繁体   中英

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 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:

$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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