Zend Framework - 在嵌套查询上应用 order by
这可能是一件非常简单的事情。查看下面的正常 sql 查询
(select * from shopping order by shopping_id desc limit 5) order by RAND()
该查询在 mysql 中成功运行 - 不确定这是否是正确的方法 - 但它有效。它从购物表中获取最后 5 个 id,并在每次
我想在 Zend 中实现此目的时随机对它们进行排序。我不确定如何执行第一部分,然后将 RAND 子句应用于结果 - 我下面的内容并没有这样做。
$select = $this->select() ->from(array('sh'=>'shopping')) ->order('shopping_id desc') ->limit(5) ->order('RAND()');
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 by 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()');
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么不采取稍微不同的方法来达到相同的结果呢?如果您删除子选择和
order by 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.Zend_Db_Expr 类可以让您做到这一点。您创建 Zend_Db_Expr 类的一个新实例,并使用其构造函数将表达式作为字符串传递:“RANDOM()”。
$select = $this->select()
->from(array('sh'=>'购物'))
->order('shopping_id desc')
->限制(5)
->order(new Zend_Db_Expr('RANDOM()'));
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()'));