我需要使用cakephp从数据库中的每个类别中提取3个结果,我尝试使用mysql会话变量和条件在数据库中查询,如下所示
SELECT *, @question_cat_rank := 0, @question_cat_country:=''
FROM
(SELECT *,
@question_cat_rank := IF(@question_cat_country = question_setname.question_cat, @question_cat_rank + 1, 1) AS question_cat_rank,
@question_cat_country := question_cat
FROM question_setname
ORDER BY question_cat desc
) ranked
WHERE question_cat_rank <= 3
它在mysql查询分析器中工作正常,但是当我使用cakephp查询时,它返回所有结果表中的3个结果
我尝试使用像下面的cakephp方式创建它
public $virtualFields = array(
'@catvirt' => 1,
'@catvirt2' => 'question_cat',
'incrmt' => 'IF(@catvirt2 = question_cat, @catvirt+1, 1)',
);
function getquestionGroup(){
$result1 = $this->find('all', array(
'fields' => array('question_cat', '@catvirt2', 'incrmt'),
'@catvirt2'=> 'question_cat',
'@catvirt' => '@catvirt'
)
);
$result = $this->find('all', array($result1,
'conditions' => array('@catvirt <=' => 3),
)
);
我试图执行准备好的语句和存储过程仍然没有运气它返回所有结果
任何帮助将不胜感激
答案 0 :(得分:0)
我会这样写这个查询:
SELECT x.*
FROM
( SELECT *
, @question_cat_rank := IF(@question_cat_country = question_cat, @question_cat_rank + 1, 1) question_cat_rank
, @question_cat_country := question_cat
FROM question_setname
, (SELECT @question_cat_rank := 0, @question_cat_country:='') vars
ORDER
BY question_cat DESC
) x
WHERE question_cat_rank <= 3;