我们假设,我有下表:(id,subject_id),在此表中我有以下记录:
id: 1, subject_id: 1 id: 2, subject_id: 1 id: 3, subject_id: 2 id: 4, subject_id: 1 id: 5, subject_id: 2
我怎样才能获得subject_id = 1的第一行和subject_id = 2的第一行:
id: 1, subject_id: 1 id: 3, subject_id: 2
答案 0 :(得分:0)
select * from (select id,subject_id FROM table group by subject_id)tempalias where subject_id=1
select * from (select id,subject_id FROM table group by subject_id)tempalias where subject_id=2
答案 1 :(得分:0)
当您使用分组时,将仅提取第一条记录。
$criteria = new CDbCriteria;
$criteria->group = 'subject_id';
$models = YouModelName::model()->findAll($criteria);
答案 2 :(得分:0)
我建议使用min(id)作为Criteria中的聚合函数[假设id是自动递增或手动递增]。
$criteria = new CDbCriteria();
$criteria->select = "min(id), subject_id";
$criteria->group = "subject_id";
$models = ModelName::model()->findAll($criteria);
没有sql函数(假设MySQL db)来获取第一行。从最新的MySQL文档中查看Group by functions。
CDbCriteria's group property与底层SQL引擎group by
功能完全相关。当没有提供显式聚合函数时,存在no default aggregate function
。 MySQL说illegal
选择你不会包含在group by
子句中的列是[{3}} [这是你没有在该列上放置聚合函数]。
MySQL文档指出,如果您选择group by
子句中未包含的[没有聚合函数]列,则结果将为indeterminate
。
同样检查这个问题:GROUP BY behavior when no aggregate functions are present in the SELECT clause