4

テーブルの最後の20エントリを取得したいのですが、IDの昇順で並べ替えます。

SQLではそれほど複雑ではありません。

SELECT * 
FROM (SELECT * FROM comments
      WHERE postID='$id' 
      ORDER BY id DESC 
      LIMIT 20) t
ORDER BY id ASC;

しかし、私は次のような私のyiiモデルでそれをやりたいと思います:

Comment::model()->findAll($criteria)

しかし、CDbCriteriaに何を入れるべきか本当にわかりません!

4

3 に答える 3

10
$models = Comment::model()->findAll(array(
    "condition" => "WHERE postID = '".$id."'",
    "order" => "id DESC",
    "limit" => 20,
));

最後の20を取得します。そして今、id ASCによって設定されたそのレコードを正しく注文したいですか?同様の結果を得るために注文できる別のフィールド(おそらく日付または作成されたフィールド)はありませんか?例:

"order" => "id DESC, created ASC"

その二次順序を破棄しますが、配列の逆順を使用しないのはなぜですか?

$models = array_reverse($models);
于 2012-10-17T20:05:42.873 に答える
4

array_reverseこのSQLを使用することを考えている場合は、を使用せずに方法があります。

SELECT * FROM `comments` `t` 
WHERE id 
in (SELECT id 
     FROM (SELECT id FROM comments Where postID = xyz ORDER BY id DESC LIMIT 20) 
    as q) 
ORDER BY id ASC

基準では次のようになります。

$criteria=new CDbCriteria();
$criteria->condition='id in (SELECT id FROM (SELECT id FROM comments Where postID='.$id.' ORDER BY id DESC LIMIT 20) as q)';
$criteria->order='id ASC';

更新

元のクエリでは、次を使用することもできますfindBySql

$sql='SELECT * FROM (SELECT * FROM comments  WHERE postID= :postid  ORDER BY id DESC LIMIT 20) q ORDER BY id ASC';
$params=array('postid'=>$id);
$comments=Comment::model()->findAllBySql($sql,$params);

このクエリのパフォーマンスは、以前のクエリよりも優れていました。

于 2012-10-17T20:44:07.037 に答える
2

UPD:

一般的に、他のいくつかの解決策が私のものよりも優れていることに注意してください。

を使用offsetすると、クエリのパフォーマンスが低下する可能性があります。http://www.slideshare.net/Eweaver/efficient-pagination-using-mysqlを参照してください。MYSQLの上限オフセットが高いとクエリが遅くなるのはなぜですか。

したがって、数Commentsが増えると、パフォーマンスが低下する可能性があります。


offset機能の使用はどうですか?

    $model = Comment::model();

    $condition = 'postID =' . $id;
    $limit = 20;
    $totalItems = $model->count($condition);

    $criteria = new CDbCriteria(array(
        'condition' => $condition,
        'order' => 'id ASC',
        'limit' => $limit,
        'offset' => $totalItems - $limit // if offset less, thah 0 - it starts from the beginning
    ));

    $result = $model->findAll($criteria);
于 2012-10-17T20:48:18.543 に答える