【问题标题】:Using order_by and group_by in CodeIgniter not working as expected在 CodeIgniter 中使用 order_by 和 group_by 无法按预期工作
【发布时间】:2014-04-11 01:06:22
【问题描述】:

我有一个测试结果表,其中每个用户和多个用户有多行。我想为每个用户返回一行,其中包含他们参加的“最近”测试的详细信息。我曾假设我可以在 CodeIgniter 中使用 order_by 和 group_by 的组合来执行此操作,但是使用这种方法不起作用,因为 CI 似乎忽略了 order_by ...:?

$this->db->where('email','email@example.com');
    $this->db->order_by('test_date', 'DESC');
    $this->db->group_by('email');
    $tmp = $this->db->get('test_results');

我怎样才能克服这个问题,而不必求助于额外的查询,但仍然能够从每个用户的“最近”测试中返回所有数据?

【问题讨论】:

    标签: mysql codeigniter group-by greatest-n-per-group


    【解决方案1】:

    您的问题与 greatest-n-per-group 标签有关,您需要为每个用户获取最近的一个结果,这应该可以解决问题,首先获取最大日期和电子邮件,然后在两个条件下使用自我加入喜欢ON(t.email =tt.email AND t.test_date=tt.test_date)

    SELECT t.* FROM 
    test_results t
    INNER JOIN (
    SELECT email,MAX(test_date) test_date FROM test_results GROUP BY email
    ) tt ON(t.email =tt.email AND t.test_date=tt.test_date)
    ORDER BY t.test_date DESC
    

    在 CI 中你可以使用查询函数来运行原始查询

    $this->db->query("SELECT t.* FROM 
    test_results t
    INNER JOIN (
    SELECT email,MAX(test_date) test_date FROM test_results GROUP BY email
    ) tt ON(t.email =tt.email AND t.test_date=tt.test_date)
    ORDER BY t.test_date DESC");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-03
      • 2017-06-17
      相关资源
      最近更新 更多