model中relations方法如下:
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'comments' => array(self::HAS_MANY, 'Comment', 'post_id',
'condition'=>'comments.status='.Comment::STATUS_APPROVED,
'order'=>'comments.create_time DESC'),
);
}
计算查询总数的sql如下:
SELECT COUNT(DISTINCT ‘t’.“id”) FROM ‘tbl_post’ ‘t’ LEFT OUTER JOIN ‘tbl_comment’ ‘comments’ ON (‘comments’.“post_id”=‘t’.“id”) WHERE (t.status=2) AND (comments.status=2);
分页查询的sql如下:
SELECT ‘t’.“id” AS “t0_c0”, ‘t’.“title” AS “t0_c1”, ‘t’.“content” AS “t0_c2”, ‘t’.“tags” AS “t0_c3”, ‘t’.“status” AS “t0_c4”, ‘t’.“create_time” AS “t0_c5”, ‘t’.“update_time” AS “t0_c6”, ‘t’.“author_id” AS “t0_c7” FROM ‘tbl_post’ ‘t’ WHERE (t.status=2) ORDER BY update_time DESC LIMIT 2;
其中LIMIT 2 是给pageSize的赋值
联表查询数据的sql如下:
SELECT ‘t’.“id” AS “t0_c0”, ‘comments’.“id” AS “t1_c0”, ‘comments’.“content” AS “t1_c1”, ‘comments’.“status” AS “t1_c2”, ‘comments’.“create_time” AS “t1_c3”, ‘comments’.“author” AS “t1_c4”, ‘comments’.“email” AS “t1_c5”, ‘comments’.“url” AS “t1_c6”, ‘comments’.“post_id” AS “t1_c7” FROM ‘tbl_post’ ‘t’ LEFT OUTER JOIN ‘tbl_comment’ ‘comments’ ON (‘comments’.“post_id”=‘t’.“id”) WHERE (‘t’.“id” IN (1, 2)) AND (comments.status=2) ORDER BY comments.create_time DESC;
我的疑问:为什么在分页查询时不联comments表,而计算查询总数时要联comments表呢?
错误的结果,见图:
3047