PHP mysqli这是最简单的方法吗?

时间:2011-07-27 21:28:47

标签: php optimization mysqli

代码段用于返回此表中每一轮的最小和最大ID。我只是想知道是否有一种不太笨重的方法来执行此操作。

$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

更改为,

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

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:2)

运行单个查询并使用WHERE round IN (....)子句更有效:

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

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

作为一般规则,执行返回“大”行数的单个查询比执行一系列一次只返回几行或一行的小/单查询更有效。您只扫描索引一次,您只需要检索一次数据。

答案 2 :(得分:1)

使用group by

在foreach中使用查询是我见过的最糟糕的做法

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