Possible Duplicate:
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 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
near 'IF( 'date created' = 'date created', ORDER BY p.created_on DESC,
ORDER BY p.' at line 17
第一个“创建日期”是可变的。所以如果 'date created' = 'date created'
,
然后 ORDER BY p.created_on DESC
else ORDER BY p.created_on ASC
使用这个:
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