我有一个充满记录的数据库,并且使用以下MySQL语法:
public static function allfood($db) {
$sql = "SELECT DISTINCT sort, sortname FROM tblDishes WHERE foodanddrinks = 'e'";
$result = $db->listing($sql);
return $result;
}
我得到所有结果按字母顺序排序。但我想确定我自己的顺序。例如,Rabbit
应该显示在 Apple
之前。是否有一种 SQL 语法允许我组织自己的显示顺序?
编辑
这在我的dbconnections.php
文件中有所说明。
public function listing($sql) {
$result = mysql_query($sql, $this->_connection);
while($row=mysql_fetch_array($result)) {
$return[] = $row;
}
return $return;
}
这是我尝试过的事情,但是我在dbconnections.php
文件中出现错误
public static function allfood($db) {
$sql = "SELECT DISTINCT sort, sortname FROM tblDishes WHERE foodanddrinks = 'e' order by case sortname
when 'Rabbit' then smth1
when 'Apple' then smth2
when 'Fish' then smth3
when 'Pasta' then smth4
when 'Snacks' then smth5";
$result = $db->listing($sql);
return $result;
}
为此,
可以向名为 DisplayOrder 的表添加另一列,然后按该列对表进行排序。
这可能有助于您:
SELECT * FROM tblDishes WHERE foodanddrinks = 'e'
order by case field_name
when 'Rabbit' then smth1
when 'Apple' then smth2
...
else smth666
end
首先,您没有对发布的代码段中的数据进行排序。如果您想要颠倒的字母顺序,只需使用:
public static function allfood($db) {
$sql = "SELECT * FROM tblDishes WHERE foodanddrinks = 'e' ORDER BY foodanddrinks DESC";
$result = $db->listing($sql);
return $result;
}
编辑:这可能也值得你花时间。 http://imthi.com/blog/programming/mysql-order-by-field-custom-field-sorting.php
这有点开销,但它应该可以工作。
如果有一个包含关键字和数字优先级的单独表,则可以在查询中添加该表的联接,然后按优先级列排序。
如果你只有十个固定的关键词,你可能会想像其他受访者建议的那样,按大小写使用顺序。 如果您有数十个关键字,或者列表是动态更新的或具有任何显着频率的,则可能需要考虑优先级查找表。
此外,如果关键字有很多重复,您可能需要考虑将它们规范化到自己的表中,并将优先级作为一个字段。