【发布时间】:2011-05-17 21:16:02
【问题描述】:
我正在尝试根据另一个表中字段的 MAX() 值在 CakePHP 中选择数据库行。这是我要执行的 SQL:
SELECT `questions`.* FROM `tests`,`questions` GROUP BY `questions`.`id` HAVING `questions`.`test_id` = MAX(`tests`.`id`);
(或等效的东西。基本上,我试图从问题表中获取所有行,其中 test_id 等于测试表中的最高 ID 值。)
我在 CakePHP 中使用 find() 能做的最接近的事情是运行两个查询:
$current_test = $this->find('first',array('fields'=>array('MAX(Test.id) as current_test')));
$questions = $this->find('all',array(
'conditions'=>array('Question.test_id'=>$current_test[0]['current_test'])
));
它得到了我需要的结果,但似乎没有必要。 CakePHP 有什么方法可以将其放入单个查询中?
【问题讨论】:
-
我个人认为 CakePHP 代码比你的 MySQL 查询要好。您在其中选择了两个没有
JOIN的表。这似乎不必要。