foreach循环中的简单select语句

时间:2017-09-29 15:01:44

标签: php mysql database performance

我在下面有一个PHP代码片段,用于检查表中的名称性别,在foreach循环中,作为优化的衡量标准,我已将LIMIT 1包含在select语句中。当我在select语句中使用EXPLAIN时,应用了索引并且行列下的值为1?

还有其他方法可以进一步改善这个吗?

foreach ($tmp as $key => $value) {
    foreach ($value as $name) {
        $statement = $dbh->prepare('SELECT gender FROM tbl WHERE names = :n LIMIT 1');
        $statement->execute(['n' => trim($name)]);
        $user = $statement->fetch(PDO::FETCH::ASSOC);
        if ($user["gender"] == "F")
            $f++;
        else if ($user["gender"] == "M")
            $m++;
        else
            $mf++;
    }
}

2 个答案:

答案 0 :(得分:1)

创建以逗号分隔的名称列表会更容易,然后将其放入类似以下查询的内容中:

SELECT sum(gender = "F") 'females', sum(gender == "M") 'males', sum(gender != "F" && gender != "M") 'other'    
FROM tbl 
WHERE names IN (:list);

然后,

$m = $user["males"];
$f = $user["females"];
$mf = $user["other"];

为什么循环查询何时足够? :)

答案 1 :(得分:0)

我认为您需要获得性别统计数据?然后你就可以直接使用SQL查询直接执行它,如下所示:

$statement = $dbh->prepare(
    "SELECT 
         count(CASE WHEN gender = 'M' THEN id END) as m, 
         count(CASE WHEN gender = 'F' THEN id END) as f, 
         count(CASE WHEN gender IS NULL THEN id END) as mf 
     FROM tbl
     WHERE names IN (?)"
);
$statement->bindValue([$name_array], [\Doctrine\DBAL\Connection::PARAM_STR_ARRAY]);
$statement->execute();
$genderStatistics = $statement->fetch(PDO::FETCH::ASSOC);

它应该更快。