mysql - 使用 CodeIgniter 中的事件记录类在一个查询中计数、分组、排序?

标签 mysql activerecord

我正在使用 CodeIgniter,我的数据库中有 2 个表。

第一个叫做大陆,看起来像这样:

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

第二次调用状态,看起来像这样:

        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

现在我想要一个按 continent_id 分组的有序列表,并从大多数记录(在我的例子中是欧洲)到最少(亚洲)的结果如下所示:

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

记录的数量并不重要,我将在内部使用另一个 foreach 循环。但我需要以某种方式在一个查询中实现计数、分组和排序事件记录功能:

到目前为止,我的模型中有这个:

function get_top_continents() {

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


    }

但我还需要根据组中的项目数量对结果进行排序。

如何做这样的order by条件?

最佳答案

$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();

关于mysql - 使用 CodeIgniter 中的事件记录类在一个查询中计数、分组、排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12082096/

相关文章:

Android:如何将从 SQL 数据库返回的每个元组作为文本放在按钮上?

mysql - 存储过程将 int 转换为十进制

zend-framework - DataMapper 模式会破坏 MVC 吗?

php - Codeigniter 数据库 Where 有多个子句,另一个 where

ruby-on-rails - Active Record has_many 生成带有外键 IS NULL 的 sql

ruby-on-rails - ActiveRecord 销毁方法 - 参数数量错误(0 代表 1)

php - 使用 URL 中变量的 MySQL 信息填充 PHP 页面

python - sql - request.form 和 INSERT INTO 格式

php - PHP 中 MySQL 的分页结果

ruby-on-rails - ActiveRecord:如何找到所有 child 都符合条件的 parent ?