两个查询与一个查询,性能

时间:2009-05-13 19:53:55

标签: php mysql performance oop

在PHP + MySQL + PDO中,它会慢得多吗

  • 按名称获取项目ID
  • 按ID
  • 获取商品数据

而不仅仅是

  • 按名称获取商品数据

后者只是一个查询,所以显然更快。前者可以提供更清晰的代码(因为项目的ID通常也是事先知道的),所以如果性能差异足够小会更好。

我正在使用的代码:

public function actionView(){

    // read http request
    ...

    // get item
    $itemModel = new Rust_Model_Item();
    try {
        $id = $itemModel->getItemIdByUrlTitle($urltitle);
        $item = $itemModel->getItem($id); // lots of data
    } catch (Rust_Model_Item_NotFoundException $e) {
        throw new FastMVC_Web_Error(404, 'Item not found');
    }

    ...

}

http://code.heukelom.net/filedetails.php?repname=rust&path=%2Ftrunk%2Flib%2Fclasses%2FRust%2FController%2FItem.php

public function getItem($ id){

    $item = $this->getItemBasics($id);

    $catModel = new Rust_Model_Category();
    $item['category'] = $catModel->getById($item['category_id']);

    $ratingModel = new Rust_Model_Rating();
    $item['rating'] = $ratingModel->getForItem($id);

    $pageModel = new Rust_Model_Page();
    $item['pages'] = $pageModel->getListForItem($id);

    $tagModel = new Rust_Model_Tag();
    $item['tags'] = $tagModel->getForItem($id);

    return $item;

}

http://code.heukelom.net/filedetails.php?repname=rust&path=%2Ftrunk%2Flib%2Fclasses%2FRust%2FModel%2FItem.php

2 个答案:

答案 0 :(得分:2)

您应该设计查询,以便在WHERE子句中使用的字段具有正确的键和索引设置,并且只使用一个查询来选择它们。

答案 1 :(得分:1)

为什么不创建一个通过id获取项目数据的单个查询,在id上放置一个索引。