I have a database filled with records and by using this MySQL-syntax:
public static function allfood($db) {
$sql = "SELECT DISTINCT sort, sortname FROM tblDishes WHERE foodanddrinks = 'e'";
$result = $db->listing($sql);
return $result;
}
I get all the results ordered alphabetically. But I would like to determine my own order. For example Rabbit
should be displayed before Apple
. Is there a SQL-syntax which allows me to organize my own order of display?
EDIT
This is stated in mydbconnections.php
file.
public function listing($sql) {
$result = mysql_query($sql, $this->_connection);
while($row=mysql_fetch_array($result)) {
$return[] = $row;
}
return $return;
}
And this is the thing I tried, but I get an error in the dbconnections.php
file
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;
}
You can do this by adding another column to the table named DisplayOrder and then Order the table by it.
This may help you:
SELECT * FROM tblDishes WHERE foodanddrinks = 'e'
order by case field_name
when 'Rabbit' then smth1
when 'Apple' then smth2
...
else smth666
end
First of all, you are not sorting the data in the snippet you posted. If you want an inversed alphabetical order, simply use:
public static function allfood($db) {
$sql = "SELECT * FROM tblDishes WHERE foodanddrinks = 'e' ORDER BY foodanddrinks DESC";
$result = $db->listing($sql);
return $result;
}
EDIT: This may be worth your while, too. http://imthi.com/blog/programming/mysql-order-by-field-custom-field-sorting.php
It's a bit of an overhead, but it should work.
If you have a separate table containing keywords and a numeric priority, you could add a join to that table in your query, and then order by the priority column.
If you've only got, say, ten fixed keywords, you'll probably want to use order by case, like other respondents have suggested. If you've got dozens of keywords, or a list that's updated dynamically or with any notable frequency, you might want to consider a priority lookup table.
Also if the keywords have a lot of repetition, you might want to think about normalising them out into their own table anyway, with priority as a field.
精彩评论