0

我有一组嵌套查询(随着时间的推移),随着更多数据输入数据库,它们会变得过于密集。除了基本查询之外,我对处理任何事情都很陌生,所以请放轻松。我已经阅读了有关联接的信息,但这些似乎对性能有类似的影响。我相信我需要在这里使用数组,但我不知道该怎么做。谢谢你帮助我学习!

$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();
4

1 回答 1

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);

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

于 2013-09-21T00:55:02.333 回答