最佳实践最大限度地减少数组查询的数量

时间:2013-09-21 00:42:14

标签: mysql sql

我有一组嵌套查询(随着时间的推移)将变得过于激烈,因为更多数据输入到数据库中。除了基本的查询之外,我还很擅长使用其他任何东西,所以请放轻松。我已经阅读了有关连接的内容,但这些似乎也有类似的性能影响。我相信我需要在这里使用数组,但我不知道如何去做。谢谢你帮我学习!

$uid = $_SESSION['uid'];
// grab list of possible procedures
$stmt = $dbh->prepare("SELECT id,name,required FROM procedures ORDER BY name");
$stmt->execute();

////loop through each procedure and see how many have been done
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $q) {
    $prid = $q['id'];
    //find sum of number completed in procedure log table
    //sql variables were cleaned earlier in code. I apparently cannot sum a column and fetch rows of data, so this query is redundant below
    $stmt2 = $dbh->prepare("SELECT sum(count) as cnt FROM procedure_log WHERE uid = '$uid' AND pid = '$prid' ORDER BY month"); 
    $stmt2->execute();
    $n = $stmt2->fetch();

    //print out list of completed procedures after the start date
    $stmt2 = $dbh->prepare("SELECT id,month,pid,other FROM procedure_log WHERE uid = '$uid' AND pid = '$prid' AND month > '2013-06-02' ORDER BY month");
    $stmt2->execute();

    //grab just number completed before the start date
    $stmt2 = $dbh->prepare("SELECT sum(count) as cnt FROM procedure_log WHERE uid = '$uid' AND pid = '$prid' AND month < '2013-06-02'");
    $stmt2->execute();  
    $o = $stmt2->fetch();

1 个答案:

答案 0 :(得分:1)

你想要的是:

$stmt = $dbh->prepare("SELECT p.id, p.name, p.required, l.month, sum(l.count) cnt
                       FROM procedures p
                       JOIN procedure_log l ON l.pid = p.id
                       WHERE l.uid = :uid
                       GROUP BY p.id, l.month
                       ORDER BY p.name, l.month");
$stmt->execute(array('uid' => $uid);

我建议你在处理结果的循环中对开始日期之前和之后的行进行计数和过滤。