0

I need to order a table but I don't know how columns will be selected by user.

Example:

select * 
from table 
order by field1, field2, field3

But the user can change fields order: field3, field1, field2

I was thinking in something like that:

select * 
from table
order by 
some_fuction (
field1, priority
field2, priority
field3, priority
)

Where I can set the priority in each field. Is it possible?

Thanks, Anderson

2 Answers2

1

Using if, case you can get a solution.
You can look at various solutions posted on SO:

  1. “IF” statement in MYSQL ORDER BY?
  2. MySQL order by multiple case statements
  3. complex sql order by
  4. MySQL : Conditional ORDER BY to only one column

and may be more ...

Community
  • 1
  • 1
Ravinder Reddy
  • 23,692
  • 6
  • 52
  • 82
  • I wouldn't like to use if or case and make something like this: select * from table order by case id when 1 then field1 when 2 then field2 end case id when 1 then field1 when 2 then field2 end . . . – user1433588 Jun 03 '12 at 16:33
  • @user1433588 - These are the only options at MySQL level. Otherwise you have to decide at server script level, before framing the sql query. – Ravinder Reddy Jun 03 '12 at 17:51
0

if the user is selecting order means... use the parameter to order filed

select * from table_name
order by ${filed_name}

case makes SQL big

Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85