如何按特定值排序行?mysql代码点火器

7hiiyaii  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(292)

我有个问题。我的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...

但我没有收到有效的结果。有人可以帮忙。第二个顺序是错误的。
箱子坏了。

wtzytmuj

wtzytmuj1#

您可以尝试以下解决方案:

<?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;

?>

希望有帮助。

wyyhbhjk

wyyhbhjk2#

我的解决方案是:在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

代码点火器代码:

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

相关问题