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 Answer