在使用Zend_Db的SQL查询中

时间:2012-02-29 02:04:12

标签: zend-framework zend-db

Zend Framework初学者在这里。我试图获取视频游戏数据库的所有Xbox标题。一张桌子包含游戏。另一个表包含游戏类型(即Xbox,Xbox Live Arcade,......)。我通常使用以下查询来获取Xbox标题。

如何使用Zend_Db执行相同的查询?

谢谢,

SELECT titleGame
FROM Game 
WHERE idGameType IN (
    SELECT idGameType 
    FROM GameType 
    WHERE nameGameType = 'Xbox')

2 个答案:

答案 0 :(得分:6)

可以通过几种方式在Zend Framework中重写。以下是我通常使用Zend_Db_Table_Select编写选择的方式。

<?php

// For brevity, $dbTable = a Zend_Db_Table object

// first construct the subquery/join for the IN clause
// SELECT idGameType FROM GameType HERE nameGameType = 'Xbox'
$subselect = $dbTable->select()
                     ->from('GameType', array('idGameType'))
                     ->where('nameGameType = ?', 'Xbox'); // quotes Xbox appropriately, prevents SQL injection and errors

// construct the primary select
// SELECT titleGame FROM Game WHERE idGameType IN (subquery)
$select = $dbTable->select()
                  ->setIntegrityCheck(false) // allows us to select from another table
                  ->from($dbTable, array('titleGame'))
                  ->where('idGameType IN (?)', $subselect);

$results = $select->query()->fetchAll(); // will throw an exception if the query fails
if(0 === count($results)) {
    echo "No Results";
}else{
    foreach($results as $result){
        echo $result['titleGame'] . '<br />';
    }
}

您也可以将SQL编写为字符串,但是在可能的情况下,面向对象的方法是理想的,因为它使查询更具可移植性,最重要的是使查询安全变得非常容易。

示例:

$db = Zend_Db_Table::getDefaultAdapter();  // get the default Db connection
$db->select("select * from table where id = 3"); // doable, but not recommended

您还可以创建prepared statementZend_Db_Statement到PHP的PDO扩展程序。

$sql = 'SELECT * FROM bugs WHERE reported_by = ? AND bug_status = ?';
$stmt = new Zend_Db_Statement_Mysqli($db, $sql);
$stmt->execute(array('goofy', 'FIXED'));

第一种方法,面向对象的流畅界面是您最常见的,以及我建议开始使用和使用的方法。

仔细阅读Zend_Db Manual Pages,特别是Zend_Db_Table_SelectZend_Db_TableZend_Db_Adapter,以获取更多信息。即使快速阅读ZF Quickstart特别关注Db部分也很有帮助。它将展示如何将表类设置为应用程序和数据库之间的网关。

答案 1 :(得分:0)

SELECT titleGame FROM Game
LEFT JOIN GameType ON GameType.idGameType = Game.idGameType
WHERE GameType.nameGameType = 'Xbox'

为什么不使用连接呢?根据我的经验,IN内的子选项在MySQL中非常慢。

$select = $db->select();
$select->from('Game', array('titleGame'));
$select->joinLeft('GameType', 'GameType.idGameType = Game.idGameType', array());
$select->where("GameType.nameGameType = 'Xbox'");