使用Active Record的分层查询

时间:2013-03-12 11:23:48

标签: mysql arrays codeigniter activerecord

我的数据库表中有记录,名为 pages

结构如:

id | parent_id | title

如果 parent_id == 0 ,则表示该行是父

如果 parent_id!= 0 ,则表示该行是儿童

我可以使用CodeIgniter activerecord获取所有记录,如:

$query = $this->db->get('pages');

结果是这样的:

Europe
Mexico
Spain
Africa
Germany
Canada
America
Egypt
France

但我需要使用某个groupby或其他东西对结果进行重新排序,以便它将db中具有相同parent_id的所有行分组,然后生成get(),结果如下:

Africa
    Egypt
America
    Canada
    Mexico
Europe
    Germany
    France
    Spain

其中parent_id = 0是非洲,美国和欧洲

埃及有例如parent_id = 1 加拿大和墨西哥parent_id = 2 等等,根据其父母的身份

怎么做?

顺便说一下。文本缩进和css没问题,我只是对foreach循环本身的结果数组感到好奇。

1 个答案:

答案 0 :(得分:2)

此查询应该这样做:

select 
    c2.id, c1.title as continent, c2.name as country
from
    country as c1
        left outer join country as c2 ON (c1.id = c2.parent_id)
where
    c2.parent_id != 0
order by c1.title , c2.title

根据您的样本数据,这将产生:

8   Africa  Egypt
6   America Canada
2   America Mexico
9   Europe  France
5   Europe  Germany
3   Europe  Spain

更新: 如果您想将大陆和国家/地区混合使用:

select 
    c2.id, c2.title as country
from
    country as c1
    left outer join
        country as c2 ON (c1.id = c2.parent_id or c1.id = c2.id and c2.parent_id = 0)
where
    c2.title is not null
order by 
    case 
        when c2.parent_id = 0 then c2.id else c2.parent_id end,
        c2.parent_id

这将为您提供以下输出:

1   Europe
3   Spain
9   France
5   Germany
4   Africa
8   Egypt
7   America
6   Canada
2   Mexico

要在codeigniter中使用,最简单的方法是不使用活动记录,只需一个简单的查询:

$sql = 'select 
    c2.id, c2.title as country
from
    country as c1
    left outer join
        country as c2 ON (c1.id = c2.parent_id or c1.id = c2.id and c2.parent_id = 0)
where
    c2.title is not null
order by 
    case 
        when c2.parent_id = 0 then c2.id else c2.parent_id end,
        c2.parent_id'

$result = $this->db->query($sql)->result();