【问题标题】:Get order of query result according to 'IN' clause in the query in cake php or mysql根据cake php或mysql中查询中的'IN'子句获取查询结果的顺序
【发布时间】:2012-04-14 18:30:17
【问题描述】:

in cake php 是我们如何根据查询中的'IN'子句获取查询结果的顺序

$array = array(8,6); // order in 'In' clause
$condition = array('Video.id' => $array);
$videos = $this->Video->find('all', array('conditions' => $conditions));

//The query will be like below
SELECT * FROM `videos` AS `Video` WHERE `Video`.`id` IN (8,6);

目前它会给出结果

Array
(
    [0] => Array
    (
        [Video] => Array
        (
            [id] => 6
        )

    )

    [1] => Array
    (
        [Video] => Array
        (
            [id] => 8
        )

    )

)

我需要它

Array
(
    [0] => Array
    (
        [Video] => Array
        (
            [id] => 8
        )

    )

    [1] => Array
    (
        [Video] => Array
        (
            [id] => 6
        )

    )

)

order Desc 或 asc 不会按顺序检索实际结果。如何使用 cake php 恢复?

我用的是cake php,在mysql中能不能做到?

【问题讨论】:

    标签: mysql cakephp cakephp-1.3


    【解决方案1】:
    SELECT * FROM table WHERE id IN (1,2,3,4,5)
    

    上面的查询可以像这样转换成 CakePHP:

    <?php
        $ids = array(1,2,3,4,5);
        $this->Model->find('all', array('conditions' => array('Model.id' => $ids)));
    ?>
    

    【讨论】:

      【解决方案2】:

      为什么不写

      SELECT * FROM `videos` as `Videos` WHERE `Videos`.`id` IN (8,6) ORDER BY `Videos`.`id` DESC
      

      SELECT 语句中使用* 不是最佳做法。 让我知道这是否有帮助。

      编辑

      如果需要,我们也可以使用其他方法对其进行排序

      Order By Case `Video`.`id`
      When 8 Then 1
      When 1 Then 2
      When 3 Then 3 
      END
      

      【讨论】:

        【解决方案3】:

        这对我来说很好用

        $order = array("FIND_IN_SET(Video.id, '8,6')");
        
        $result = $this->Video->find('all', array('conditions' => $conditions,'order' => $order);
        

        【讨论】:

          【解决方案4】:
          ORDER BY FIELD("videos"."id",8,6)
          

          我相信你可以在 cake's find 中使用它

          您甚至可以通过这种方式使用 ELT 功能:

          ORDER BY ELT(videos.id, 8,1,6,2,n,3,.....)
          

          【讨论】:

            【解决方案5】:

            ORDER 是 CakePHP 中的一个选项?

            $this->Video->find('all', array('conditions' => $conditions, 'order' => array('Video.id DESC')));
            

            回应评论:

            $this->Video->find('all', array('conditions' => $conditions, 'order' => array('FIELD(Video.id, 7, 4, 9)')));
            

            【讨论】:

            • 如果您搜索 id IN (7,4,9) 并想要广告订单 7-4-9 怎么办?
            • 所以你实现了我的解决方案:)
            • 嗯,这是解决方案,所以是的。 :)
            • 感谢您的回答,效果很好。这样我也得到了想要的结果'order' =&gt; array("FIND_IN_SET(Video.id, '8,6')")
            猜你喜欢
            • 1970-01-01
            • 2018-07-15
            • 2012-04-30
            • 2015-04-02
            • 1970-01-01
            • 2010-11-25
            • 2010-12-10
            • 2020-07-20
            • 1970-01-01
            相关资源
            最近更新 更多