0

我目前正在重构一个遗留应用程序并逐个转换为 zend 框架 1.12。

我对如何将其转换为 zend db 感到头疼,有没有一种方法可以在一个查询中完成?

现在我看到它首先获取文件夹列表,然后为每个文件夹运行一个额外的查询......作为一个查询运行它会提高性能,对吗?

$folders_query = DB::Query("select * from contacts_folders order by sort_order, name");
while($folders = DB::FetchArray($folders_query)){
    $counts_total = DB::QueryOne("SELECT count(cm.messages_id) AS total
    FROM contacts_basics cb, contacts_messages cm
    WHERE cb.contacts_id = cm.contacts_id
    AND cm.folders_id =  '" . $folders['folders_id'] . "'
    AND cm.status = '1'
    AND cm.mark =  '0'");


    if ($counts_total >0){ 
        $folders_name = '<strong>' . $folders['name'] . ' (' . $counts_total . ')</strong>'; 
    } else { 
        $folders_name = $folders['name']; 
    }

    echo '<li><a href="messages.php?fID=' . $folders['folders_id'] . '">';

    echo $folders_name;

    echo '</a></li>';
}
4

2 回答 2

2

是的,您可以在同一个查询中同时执行这两项操作

SELECT cf.*, count(cm.messages_id) AS total
FROM contacts_folders cf left outer join
     contacts_messages cm
     on cf.id = cm.folders_id and
        cm.status = '1' AND cm.mark =  '0' left outer join
     contacts_basics cb
     on cb.contacts_id = cm.contacts_id
group by cf.folders_id
order by cf.sort_order, cf.name;

这使用 aleft outer join来确保您获得所有文件夹,即使没有消息(这是原始代码的工作方式)。由于left outer join,条件需要移动到on子句中。

它还从文件夹中获取所有信息以及总数。如果没有消息,那么它应该为该文件夹返回 0。

于 2013-06-23T17:27:11.723 回答
0

戈登的回答中有一个小错误,但多亏了他,我才弄清楚了。

我变了

contacts_basics cb left outer join

至:

left outer join contacts_basics cb

以下代码按预期工作:

public function getMenuCounts(){
    $raw = "SELECT cf.*, count(cm.messages_id) AS total
    FROM contacts_folders cf left outer join
    contacts_messages cm
    on cf.folders_id = cm.folders_id and
    cm.status = '1' AND cm.mark =  '0'
    left outer join contacts_basics cb
    on cb.contacts_id = cm.contacts_id
    group by cf.folders_id
    order by cf.sort_order, cf.name;";
    $db = Zend_Db_Table::getDefaultAdapter();
    $stmt = $db->query($raw);
    return $stmt->fetchAll();
}
于 2013-06-23T18:22:10.980 回答