0

我的数据库表中有名为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 等根据其父母的 id

怎么做?

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

4

1 回答 1

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();
于 2013-03-12T11:58:39.580 回答