MySQL:如何使用ORDER的IF条件

时间:2012-04-19 01:39:08

标签: php mysql sql

  

可能重复:
  Can you add “IF” statement in PHP MYSQL ORDER BY?

如何在MySQL中使用ORDER的IF条件?

例如,我的下面的查询返回错误

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
)

消息

  

1064 - 您的SQL语法出错;检查与MySQL服务器版本对应的手册,以获得正确的语法   'IF('创建日期'='创建日期',ORDER BY p.created_on DESC附近,   订购p。'在第17行

第一个'创建日期'是可变的。如果是'date created' = 'date created'

然后ORDER BY p.created_on DESC

其他ORDER BY p.created_on ASC

1 个答案:

答案 0 :(得分:5)

使用此:

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

实时测试: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

实时测试:http://www.sqlfiddle.com/#!2/f78f3/3