如何按特定值对行进行排序?MySQL CodeIgniter

4

我有一个问题。 当我尝试按特定值排序时,我的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语句不正确。


@JayBlanchard 的问题不是关于如何一般性地排序,而是关于如何按照 CASE 结果的值进行排序。 - u_mulder
3
不确定CodeIgniter的具体情况,但尝试将CASE语句作为SELECT中的一列添加一个别名,然后尝试按别名排序。 - flip
@flip 谢谢,我会尝试的。;) - danplaton4
@DanPlaton,您能否发布CodeIgniter生成的查询和您期望的结果? - flip
@flip 我已经找到了解决方案。谢谢。 - danplaton4
显示剩余3条评论
2个回答

3
您可以尝试以下解决方案来解决您的问题:
<?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
我建议的解决方案是: 在CodeIgniter模型中选择一个包含所有按顺序排列的结果的视图。
示例:
select (case when (`parajurist`.`intrebari`.`Status` = 2) then 1 else 2 end) 
AS `Second`,`parajurist`.`intrebari`.`IdIntrebare` AS 
`IdIntrebare`,`parajurist`.`intrebari`.`Titlu` AS 
`Titlu`,`parajurist`.`intrebari`.`Descriere` AS 
`Descriere`,`parajurist`.`intrebari`.`NumePrenumeP` AS 
`NumePrenumeP`,`parajurist`.`intrebari`.`EmailP` AS 
`EmailP`,`parajurist`.`intrebari`.`Status` AS 
`Status`,`parajurist`.`intrebari`.`IdCategorie` AS 
`IdCategorie`,`parajurist`.`intrebari`.`DataAdresare` AS 
`DataAdresare`,`parajurist`.`intrebari`.`Comments` AS 
`Comments`,`parajurist`.`intrebari`.`CuvCheie` AS `CuvCheie` from 
(`parajurist`.`intrebari` join `parajurist`.`intrebaricategorii` 
on((`parajurist`.`intrebaricategorii`.`IdCategorie` = 
`parajurist`.`intrebari`.`IdCategorie`))) where 
(`parajurist`.`intrebari`.`Status` <> 0) order by (case when 
(`parajurist`.`intrebari`.`Status` = 2) then 1 else 2 
end),`parajurist`.`intrebari`.`IdIntrebare` desc

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接