3

可能重复:
您可以在 PHP MYSQL ORDER BY 中添加“IF”语句吗?

如何在 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 服务器版本相对应的手册,以在第 17 行的 'IF('date created' = 'date created', ORDER BY p.created_on DESC, ORDER BY p.' 附近使用正确的语法

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

然后ORDER BY p.created_on DESC

别的ORDER BY p.created_on ASC

4

1 回答 1

6

用这个:

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

于 2012-04-19T01:56:35.957 回答