tags:

views:

74

answers:

3

Hi, I have many rows in a mysql table. There is an order_id column. I want to order by two columns, first by order_id and next by id(auto increment). The problem is that i entered 1, 2, 3, 4, 5... for order_id and leave blank for the others. In my example i want to display first the rows that has the numbers 1, 2, 3, 4 but instead it shows the rows with blank order_id since that is less than 1. Is there a way to start the order at 1?

Example:

id | order_id | name
1  | NULL     | test name 1
2  | 1        | test name 2
3  | NULL     | test name 3
4  | 2        | test name 4
5  | 3        | test name 5

I would like my order statement to give the following result

test name 2
test name 4
test name 5
test name 1
test name 3

As you can see from the example i first order by the "order_id" column starting at 1

Thanks for any help.

A: 

You could try to enhance you query with a ifnull function. So you could check if order_id is null when it is order by autoincrement else order by order id See the documentation of mysql: http://dev.mysql.com/doc/refman/4.1/en/control-flow-functions.html

Bloeper
+1  A: 

If you want to omit rows with order_id, then just add a where clause (where order_id is not null). Otherwise, try adding a column to the select like this:

if(order_id IS NULL or order_id='', 1, 0)

and then sort ASC on this column first, which will put non-null order_id first.

Jim Garrison
+4  A: 

Are the missing values represented with NULL? If so then something like this should do the trick:

SELECT *
FROM your_table
ORDER BY IF(order_id IS NULL, 1, 0), order_id, id

If the missing values aren't NULL then you'll need to alter your IF clause accordingly. For example, if the missing fields are actually empty strings then you would probably use something like this instead:

SELECT *
FROM your_table
ORDER BY IF(order_id = '', 1, 0), order_id, id
LukeH
Thank you for the reply, this should work great:)
markie
If the missing fields are strings, I'd say this user is using the wrong data type for the order_id column. ;)
R. Bemrose
@R. Bemrose: Not necessarily, I guess it depends on the actual data. For example, it's not uncommon to see IDs that look something like "A1116XYZ5" etc. (Still, there's no excuse for using empty strings rather than `NULL` to represent the unknown values.)
LukeH
Anyway, markie has now updated the question and confirmed that it's an integer field and the "blanks" are actually `NULL`.
LukeH