PHP sql 查询按名称排序,并在末尾排序名为“x”的类别


PHP sql query to order by name and order at the end the category named "x"

嗨,我有一个查询,我制作一个数组来回显具有父 ID (X) pid 的所有类别。

我知道如何按名称对它们进行排序 问题出在它们中的每一个内部,这是一个称为"其他"的子类别......这个必须在最后。 因此,所有"兄弟"子类别都按字母顺序排序,类别名称"其他"位于该数组的末尾。

你怎么做

$sql="select id,name,image from categories where pid=?";
                        $res1=$db->execute_query($sql,array($row['id']));
                        while($row1=$res1->fetch_assoc())

要将other类别放在末尾,您可以这样做

order by case when cat_name = 'others' then 2 else 1 end asc,
         cat_name asc, 
         name asc

另一种仅在mySQL中起作用的方式,

ORDER BY (cat_name = 'others'), cat_name 

表达式 (cat_name = 'others') 返回 0 表示假,返回 1 表示真。