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
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
$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();
or if you have a User model (I think this will work - I didn't test either of these ;)
$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
回答2:
Haven't tested it. But it could work like this
$user = User::model()
->with('post')
->findAll(
array(
'select'=>array('id','username','score','totalPost'=>'count(ownerId)'),
'group'=>'id',
'order'=>'score DESC,totalPost DESC'
)
);