MySQL: how to use IF condition for ORDER

Possible duplicate:
Can you add an IF statement to PHP MYSQL ORDER BY?

How can I use the IF condition for ORDER in MySQL?

For example, my query below returns an error,

SELECT *
FROM page AS p

WHERE p.parent_id != p.page_id
AND p.type = 'post'
AND p.parent_id = '7'


IF(
    'date created' = 'date created', 
    ORDER BY p.created_on DESC,
    ORDER BY p.created_on ASC
)

message,

1064 - You have an error in the SQL syntax; check the manual corresponding to the version of MySQL server to use the syntax correctly next to "IF (" date created "=" date created ", ORDER BY p.created_on DESC, ORDER BY page 'on line 17

The first ' date created ' is a variable. Therefore, if 'date created' = 'date created',

then ORDER BY p.created_on DESC

else ORDER BY p.created_on ASC

+3
source share
1 answer

Use this:

create table person
(
  name varchar(50)
);


insert into person(name)
select 'John' union
select 'Paul' union
select 'George' union
select 'Ringo' ;



set @direction = 1;

-- the '' is ignored on sorting since they are all the same values
select * from person
order by 
    IF (@direction = 0, name,'') ASC,
    IF (@direction = 1, name,'') DESC

Live test: http://www.sqlfiddle.com/#!2/22ea1/1

- -1 , +1 , , :

create table person
(
  name varchar(50), birth_year int
  );


insert into person(name, birth_year)
select 'John', 1940 union
select 'Paul', 1941 union
select 'George', 1943 union
select 'Ringo', 1940 ;


set @direction = -1;  -- -1: descending, 1: ascending

select * from person
order by birth_year * @direction

Live test: http://www.sqlfiddle.com/#!2/f78f3/3

+5

All Articles