php - 如何订购查询

标签 php mysql arrays yii yii1.x

我有一个数组$sorted_array它的值是

Array ( [0] => 3 [1] => 1 [2] => 6 )

现在基于 $sorted_array 我创建了一个数组

$first_array = Yii::app()->db->createCommand()
            ->select('*')
            ->from('form_fields')                                      
             ->where(array('not in', 'id', $sorted_array))
             ->andWhere('form_id=:form_id', array(':form_id'=>$form_id))
             ->queryAll();

$sorted_array 值是表 form_fields 的 id(主键)。

当我运行此查询时,我得到数组 $first_array 但不是按照我想要的顺序。即,我将按顺序获得一个数组 $id=1,3,6。

现在我想要的顺序是 3,1,6(与 $sorted_array 完全相同)。我怎样才能按这个顺序获得$first_array

最佳答案

您可以使用 ->order() 将 order( 'id' ) 添加到您的代码中:

 $first_array = Yii::app()->db->createCommand()
        ->select('*')
        ->from('form_fields')                                      
         ->where(array('not in', 'id', $sorted_array))
         ->andWhere('form_id=:form_id', array(':form_id'=>$form_id))
         ->order('id')
         ->queryAll();

否则,如果无法使用查询构建器构建所需的查询,则可以使用

Yii::app()->db->createCommand("select * from your_table")->queryAll();

以及绑定(bind)参数

Yii::app()->db->createCommand(
        'select * from your_table  where yuor_field =:your_param')->
      bindValue('your_param',$yuor_value)->queryAll();

这将使用指定的 SQL 语句返回所有行

$sql = "select * from form_fields 
       where id not in (3,1,6) 
       and form_id = " . $form_id .
       "order by field(id, 3,6,1);";

$first_array = Yii::app()->db->createCommand($sql)->queryAll();

关于php - 如何订购查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34854708/

相关文章:

c - 数组的值在执行期间随机变化

php - PHP函数中的 session

javascript - 传递给javascript中的函数时出现Uncaught ReferenceError

php - 从数据透视表中获取特定列值

php - 分页在 Laravel 4 中不起作用

mysql - mysql 中的 varchar 和复合主键?

javascript - 对json转XML后的结果进行排序

php - 自定义页面模板无法识别 <head> 中定义的 CSS 变量

php - 通过命令行或 PHP 以 json 格式导出 mysql 数据库/mysql 表

Java - 2 float 类型的数组 - 发现可能存在精度损失 : float required : int