Zend Framework - 在嵌套查询上应用 order by

发布于 2024-08-26 13:47:15 字数 475 浏览 6 评论 0原文

这可能是一件非常简单的事情。查看下面的正常 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

∞梦里开花 2024-09-02 13:47:15

为什么不采取稍微不同的方法来达到相同的结果呢?如果您删除子选择和order by RAND(),您可以非常快速地从数据库中获取行,然后当您处理这些行时,您始终可以将它们随机化。

$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);

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);
冬天旳寂寞 2024-09-02 13:47:15

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()'));

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文