根据cake php或mysql中的查询中的'IN'子句获取查询结果的顺序

时间:2012-03-31 06:41:30

标签: mysql cakephp cakephp-1.3

在蛋糕中,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
        )

    )

)

订单描述或asc不会按顺序检索实际结果。如何使用cake php进行后退?

我正在使用cake php,这是否可以在mysql中完成?

5 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

ORDER BY FIELD("videos"."id",8,6)

我引用肯定你可以在蛋糕的发现中使用它

您甚至可以这样使用ELT功能:

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

答案 2 :(得分:0)

这对我来说很好用

$order = array("FIND_IN_SET(Video.id, '8,6')");

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

答案 3 :(得分:0)

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

答案 4 :(得分:-1)

为什么不写

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