【问题标题】:codeigniter database query / mysqlcodeigniter 数据库查询 / mysql
【发布时间】:2012-05-08 14:24:20
【问题描述】:

我用 codeigniters 数据库库写了一个查询,看起来像这样,

public function getCandidateCredits($candidate_id)
{
    $this->db->select('*')
    ->from('credits')
    ->join('candidate_has_credits', 'candidate_has_credits.credits_credit_id = credits.credit_id', 'left')
    ->where('credits.candidates_candidate_id', (int)$candidate_id)
    ->order_by('candidate_has_credits.date_created', 'DESC')
    ->order_by('credits.credit_position', 'DESC');



    $query = $this->db->get();

    return $query->result_array();
}

这个查询的意思是,获取所有成员的积分,然后按日期(最新的在前),然后按积分位置(最高的数字在前)对它们进行排序。

我遇到了一些问题,积分应该按日期排序,但前提是没有积分位置,如果有积分位置 (0 - 999),那么在订购积分时应该优先,如果有日期和信用位置,那么信用应该按信用位置和日期排序。

这可能吗?我觉得我离我需要的地方很远,我返回的结果似乎是返回没有明显的顺序。不确定是否有区别,但 date_created 字段是 DATETIME。

【问题讨论】:

  • 您肯定只是想交换ORDER BY 子句吗?

标签: php mysql database codeigniter


【解决方案1】:

您正确地使用了左连接,但是将 order by 子句的顺序错误,所以首先,翻转它们:

->order_by('credits.credit_position', 'DESC')
->order_by('candidate_has_credits.date_created', 'DESC')

应该这样做,除了现在那些没有相应信用记录的 Candidate_has_credit 行(因此 credit_position 为空)将在最后,我假设你想要那些在顶部。

在使用 DESC 排序时,如果您知道该字段中可用的最大值,有一个小技巧可以将空值推到顶部:

->order_by("ifnull('credits.credit_position',1000) desc,candidate_has_credits.date_created desc")

请注意,我使用的是 order_by 方法的形式,它只包含一个参数,不应该转义函数并且速度略快。

查看ifnull documentation 以了解其工作原理。

【讨论】:

    【解决方案2】:

    这是一个缩短的版本:

    public function getCandidateCredits($candidate_id)
    {
        return $this->db->from('credits')
        ->join('candidate_has_credits', 'candidate_has_credits.credits_credit_id = credits.credit_id', 'left')
        ->where('credits.candidates_candidate_id', (int)$candidate_id)
        ->order_by('credits.credit_position', 'DESC')
        ->order_by('candidate_has_credits.date_created', 'DESC')
        ->get()->result_array(); 
    }
    

    【讨论】:

      猜你喜欢
      • 2015-04-06
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      • 1970-01-01
      • 2012-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多