如何按特定值排序? MySQL CodeIgniter

时间:2018-01-17 13:16:55

标签: php mysql codeigniter

我有一个问题。 当我尝试按特定值排序时,我的sql查询在codeigniter中不起作用 这是一个例子:

$this->db->select('*');
$this->db->from('Questions');
$this->db->where('Questions.Status !=', 0);
$this->db->order_by('IdQuestion', 'DESC');
$this->db->order_by('(CASE WHEN Status = 3 THEN 1 ELSE 2 END)', 'DESC'); //Here's wrong...

但我没有收到有效的结果。 有人可以提供帮助。 第二个order_by语句是错误的。

CASE无效。

2 个答案:

答案 0 :(得分:2)

您可以针对您的问题尝试此解决方案:

<?php 

$sub_query_from = '(SELECT Questions.*, (CASE WHEN Questions.Status = 3 THEN 1 ELSE 2 END) as questions_status from Questions  WHERE Questions.Status != 0 ORDER BY IdQuestion DESC) as sub_questions';
$this->db->select('sub_questions.*');
$this->db->from($sub_query_from);
$this->db->order_by('sub_questions.questions_status', 'DESC');
$query = $this->db->get();
$result = $query->result();

echo "<per>";
print_r($result);
exit;

?>

希望它会有所帮助。

答案 1 :(得分:1)

我的解决方案是: 要创建包含所有已排序结果的视图,请在codeigniter模型中选择此视图

示例:

$this->db->limit($start, $stop);

    $this->db->select('*');
    $this->db->select('LEFT(intrebari_view.Titlu, 50) as Titlu');
    $this->db->select('LEFT(intrebari_view.Descriere, 150) AS Descriere');
    $this->db->join('IntrebariCategorii', 'IntrebariCategorii.IdCategorie = intrebari_view.IdCategorie');
    $this->db->where('IntrebariCategorii.NumeCategorie', $cat);
    $this->db->from('intrebari_view');
    $query = $this->db->get();

和codeigniter代码:

$(window).scroll(function() {

    console.log($(this).scrollTop());
    if ($(this).scrollTop() > 200) { //use `this`, not `document`
        $(".box").stop().animate({'opacity':'1'}, 1000);
    }
    
    if ($(this).scrollTop() < 200) { //use `this`, not `document`
        $(".box").stop().animate({'opacity':'0'}, 1000);
    }
});