Forum Moderators: coopster
Depending on how you display it, when you loop through the rows, you can collect the ones having the $row[thevalue] == 0 into a variable, and then attach them back again at the end.
I would have done something similar.
Ofcourse, there could be easier ways out of this.
SELECT foo FROM bar ORDER BY foo = 0, foo ASC
Zeros are always the last results and the remaining results are sorted with ASC and DESC as they normally would be.
Left to right reading logic tells me that any result which equals 0 would be first, but that's not the case. To get zeros first you would put
foo = 0 last in the ORDER BY criteria. I couldn't immediately find the section of the mysql docs about using multiple criteria in the
ORDER BY statement, but if someone else knows where it is I'd appreciate a link. This is working for me but I don't exactly understand how or why. Thanks for the input.
[edited by: SixTimesEight at 1:41 pm (utc) on Sep. 8, 2007]
any result which equals 0 would be first, but that's not the case.
Yes, actually it is the case. You are just misunderstanding what the result should be ... explanation coming in a moment, first ...
To get zeros first you would put foo = 0 last in the ORDER BY criteria
Not necessary, just leave it out entirely and just ORDER BY foo and the zeros will come first by natural order of integers -- you must have been thinking too hard on this one ;)
I couldn't immediately find the section of the mysql docs about using multiple criteria in the ORDER BY statement, but if someone else knows where it is I'd appreciate a link.
The ORDER BY definition is in the SELECT [dev.mysql.com] statement syntax and can have values of
[ORDER BY {col_name ¦ expr ¦ position} [ASC ¦ DESC], ...] where expr is an expression. Note that the use of
positionis deprecated because the syntax has been removed from the SQL standard.
Now for an explanation as mentioned earlier. You are misunderstanding your sort order definition. The definition "n1 = 0" is an expression which is going to return true or false when it compares the value of n1 for each row to the constant value of zero. The reason for your sort order is because your expression is returning TRUE for only those rows where foo = 0. Example, for clarification ...
CREATE TABLE mynumbers (n1 INTEGER UNSIGNED);
INSERT INTO mynumbers (n1) VALUES(4),(2),(0),(3),(1);
SELECT n1 FROM mynumbers ORDER BY n1 = 0, n1;
+----+
¦ n1 ¦
+----+
¦ 1 ¦
¦ 2 ¦
¦ 3 ¦
¦ 4 ¦
¦ 0 ¦
+----+
SELECT n1 = 0 AS nn, n1 FROM mynumbers ORDER BY n1 = 0, n1;
+----+----+
¦ nn ¦ n1 ¦
+----+----+
¦ 0 ¦ 1 ¦
¦ 0 ¦ 2 ¦
¦ 0 ¦ 3 ¦
¦ 0 ¦ 4 ¦
¦ 1 ¦ 0 ¦
+----+----+
A UNION is going to be fastest, by the way.
(SELECT 1 AS sort_col, n1 FROM myNumbers WHERE n1 > 0 ORDER BY n1)
UNION ALL
(SELECT 2 AS sort_col, n1 FROM myNumbers WHERE n1 = 0 ORDER BY n1)
ORDER BY sort_col, n1;