0
SELECT u.id, u.username, u.score,
(SELECT COUNT(ownerId) FROM post p WHERE p.ownerId = u.id) AS totalPost
FROM users u
ORDER BY u.score DESC, totalPost DESC LIMIT 10
SELECT u.id, u.username, u.score,
(SELECT COUNT(ownerId) FROM post p WHERE p.ownerId = u.id) AS totalPost
FROM users u
ORDER BY u.score DESC, totalPost DESC LIMIT 10
$sql = "SELECT u.id, u.username, u.score, ".
"(SELECT COUNT(ownerId) FROM post p WHERE p.ownerId = u.id) AS totalPost ".
"FROM users u ".
"ORDER BY u.score DESC, totalPost DESC ".
"LIMIT 10";
$command=Yii::app()->db->createCommand($sql);
$results=$command->query();
,或者如果你有一個用戶模型(我認爲這會工作 - 我沒有測試其中任一;)
$criteria = new CDbCriteria();
$criteria->select = "t.id, t.username, t.score, (SELECT COUNT(ownerId) FROM post p WHERE p.ownerId = t.id) AS totalPost";
$criteria->order = "u.score DESC, totalPost DESC";
$criteria->limit = "10";
$results = User::model()->findAll($criteria); // this returns an array of User models
還沒有測試過。但它可能像這樣工作
$user = User::model()
->with('post')
->findAll(
array(
'select'=>array('id','username','score','totalPost'=>'count(ownerId)'),
'group'=>'id',
'order'=>'score DESC,totalPost DESC'
)
);
http://www.yiiframework.com/doc/guide/1.1/en/database.dao – 2011-02-10 11:38:24
請記住,以及利用網絡調試吧,它會顯示你查詢正在執行。這可以幫助你寫代碼,因爲你可以看到你離你想要的距離有多遠。 – 2011-02-10 11:44:34
你是什麼意思「轉換」?你只是想直接執行它?或者你有一個用戶模型,你想使用CDBCriteria查詢這些用戶? – thaddeusmt 2011-02-10 16:03:23