简化为:
$q = mysql_query("SELECT * FROM mytable ORDER BY category") or die(mysql_error());
while($row = mysql_fetch_array($q)) {
$cat = $row['category'];
echo $cat."<br />";
}
mytable
持有Apple,Banana,Citrus
我希望结果以特定顺序显示,例如Banana,Apple,Citrus。
如何查询?
答案 0 :(得分:2)
取自http://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html
的回复“如果你想明确指定'order by'的顺序,就好像你有一个优先级字段,其值为”Low“”High“或”Medium“..执行此操作:
select * from tablename order by priority='High' DESC, priority='Medium' DESC, priority='Low" DESC;"
对于您的情况,这将是:
$q = mysql_query("SELECT * FROM mytable ORDER BY category='Banana' DESC, category='Apple' DESC, category='Citrus' DESC") or die(mysql_error());
while($row = mysql_fetch_array($q)) {
$cat = $row['category'];
echo $cat."<br />";
}
答案 1 :(得分:2)
您可以使用order by field(...)
:
SELECT * FROM mytable ORDER BY FIELD(category, 'Banana', 'Apple', 'Citrus');
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_field - FIELD()函数手册。