2011-11-15 152 views
-1

我尝试了自己的另一个查询,但这个对我来说比较复杂,因为我是zend新手。请帮助我,我尝试了不同的方式,但没有奏效。如何在zend数据库中执行sql查询

Tour Id fetching from another query 

$tourId = $row2 ['test_public_id']; 

$query = select count(ms.test_public_id) as total_views, ms1.recent_views from test_stats 
ms join (select count(test_stats.test_public_id) as recent_views 
from test_stats where test_stats.test_public_id = '$tourId' 
and test_stats.updated_on > DATE_SUB(CURDATE(), INTERVAL 7 DAY)) ms1 
where ms.test_public_id ='$tourId'" ; 
+0

描述什么“没有工作” - 错误消息,意想不到的结果等将是有用的。例如,您显示的代码缺少引用('$ query ='之后和'select'之前),但可能会只是一个错字。更多信息会很好。 – StasM

回答

1

类似的东西应该工作:

$subselect = $dbAdapther->select()->from(
    array('test_stats' => 'test_stats'), 
    array(
    '(COUNT(test_public_id)) AS recent_views' 
) 
)->where(
    $dbAdapther->quoteInto('test_stats.test_public_id = ?', $tourId) 
)->where(
    'test_stats.updated_on > DATE_SUB(CURDATE(), INTERVAL 7 DAY)' 
); 

$select = $dbAdapther->select()->from(
    array('ms' => 'test_stats'), 
    array(
    '(COUNT(ms.test_public_id)) AS total_views' // COUNT should be in brackets to preevent Zend from interpreting it as a field name 
) 
)->join(
    array('ms1' => $subselect), 
    '', 
    array(
    'ms1.recent_views' 
) 
)->where(
    $dbAdapther->quoteInto('ms.test_public_id = ?', $tourId)' 
); 

虽然我有你的查询分为两个单独的查询,或者更确切地说,写一个通用的“获取视图数”查询,并将日期作为其参数,然后我会调用它两次,不论是否有日期。

但是如果你仍然需要在一行中一次性得到这两个数字(即你不能使用UNION而不是你不必要的JOIN),我建议你使用下面的代码来代替:

$select = $dbAdapther->select()->from(
    array('ms' => 'test_stats'), 
    array(
    '(COUNT(ms.test_public_id)) AS total_views', 
    '(
     COUNT(
     CASE 
      WHEN ms.updated_on > DATE_SUB(CURDATE(), INTERVAL 7 DAY)) THEN ms.test_public_id 
      ELSE NULL 
     END 
    ) 
    ) AS recent_views' 
) 
)->where(
    $dbAdapther->quoteInto('ms.test_public_id = ?', $tourId) 
); 
0

我在Zend也是新的,但我已经尝试过这个示例,它的工作原理。 参见本教程中,我希望它会帮助你: http://framework.zend.com/manual/en/zend.db.select.html

,或者你可以这样做:

$db = Zend_Db_Table_Abstract::getDefaultAdapter(); 
$stmt = $db->query($query); 
$result = $stmt->fetchAll(); 
相关问题