php - codeigniter数据库查询/mysql

标签 php mysql database codeigniter

我用 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();
}

此查询的目的是获取所有成员(member)信用,并首先按日期(最新的在前),然后按信用位置(最高的数字在前)对它们进行排序。

不过,我遇到了一些问题,学分应该按日期排序,但前提是没有学分位置,如果有学分位置(0 - 999),那么在订购学分时应该优先考虑,如果有日期和片尾字幕,则片尾字幕应按片尾字幕排序,然后是日期。

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

最佳答案

您正确地使用了左连接,但将 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看看它是如何工作的。

关于php - codeigniter数据库查询/mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10500534/

相关文章:

php - 无法显示好友列表

java - 将 byte[] 映射到 jOOQ 中的 BLOB 在查询中变为 NULL

PHP MySQL数据库设计

MySQL - 从行中创建列

php - 如何在wordpress页面上以不同格式显示第一篇文章?

PHP & MySQL 用户名验证和存储问题

php - 在 Symfony 服务中使用 session

mysql - 如何在 sql 请求中添加条件?

database - 测量 Postgres 中的实际查询性能

android - SQLite 数据库最大存储容量