开发者

Zend Framework - applying order by on a nested query

This might be a very simple thing. Check out the normal sql query below

(select * from shopping order by shopping_id desc limit 5) order b开发者_如何学Pythony RAND()

This query runs successfully in mysql - not sure if this is the right way of doing it - but it works. It gets the last 5 ids from shopping table and randomly orders them everytime

I want to achieve this in Zend. I'm not sure how to execute the first part and then apply the RAND clause to the results - what I have below does not do that.

$select = $this->select()       
           ->from(array('sh'=>'shopping'))
           ->order('shopping_id desc')
           ->limit(5)    
           ->order('RAND()');


Why not take a slightly different approach which will acheive the same results. If you drop the subselect and the order by RAND() you can get the rows very quickly from the database, then when you are working with the rows, you could always randomize them.

$select = $this->select()       
       ->from(array('sh'=>'shopping'))
       ->order('shopping_id desc')
       ->limit(5)    

$rows = $this->fetchAll($select);

// take it from a rowset object, convert to an array:
$rowArray = array();
foreach ($rows as $row) $rowArray[] = $row;
shuffle($rowArray);


The Zend_Db_Expr class lets you do that. You create a new instance of the Zend_Db_Expr class and using its constructor you pass in the expression as a string: "RANDOM()".

$select = $this->select()
->from(array('sh'=>'shopping')) ->order('shopping_id desc') ->limit(5)
->order(new Zend_Db_Expr('RANDOM()'));

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜