1
votes

I am using CodeIgniter and I have 2 tables in my database.

1st called continents and looks like this:

    id     | continent_name
    -----------------------
    1      | Africa
    2      | Antarctica
    3      | Asia
    4      | Australia
    5      | Europe
    6      | North America
    7      | South America

2nd called states and looks like this:

        id | continent_id  | country_name
        -----------------------------------
        1  | 5             | Denmark
        2  | 1             | Angola
        3  | 7             | Peru
        4  | 5             | Germany
        5  | 7             | Venezuela
        6  | 1             | Egypt
        7  | 5             | Spain
        8  | 5             | France
        9  | 7             | Argentina
        10 | 6             | Canada

And now I want an ordered list grouped by continent_id and oredered from most records (in my case Europe) to the least (Asia) result like this:

Europe (4)
South America (3)
Africa (2)
North America (1)
Asia (0)

The number of records is not important I will be using another foreach loop inside. But I need somehow achieve the count, group and order active record functions in one query:

So far I have this in my model:

function get_top_continents() {

            $q = $this->db->from('states')
                          ->join('continents', 'states.continent_id = continents.id')
                          ->group_by('continent_id')
                          ->get();
            return $q;


    }

But I need to order the result also on the number of items in group.

How to do such order by condition?

1

1 Answers

2
votes
$q = $this->db->select('continents.id as continent_id,max(continents.continent_name) as   continent_name, COUNT(states.id) as states_count',FALSE)
                      ->from('continents')
                      ->join('states', 'continents.id=states.continent_id','left')
                      ->group_by('continents.id')
                      ->order_by('states_count', 'desc');
                      ->get();