php - MySQL:如何对 ORDER 使用 IF 条件

标签 php mysql sql

<分区>

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

关于php - MySQL:如何对 ORDER 使用 IF 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10220511/

相关文章:

php - 查找 HTML 中最里面的文本

php - 使用 PHP 和 JavaScript 的动态 CSS

php - 从不同的值创建单个数组

php - json对象与ajax返回数组的用法

php - mysql中如何获取值不为null的列名

java - 为什么 JPA TypedQuery 抛出异常 : Parameter value [. ..] 与预期类型 [java.lang.Character] 不匹配?

sql - 错误 3265 - 记录集中存在字段

mysql - 查询统计出现次数最多的前三项

sql - PostgreSQL 错误 : payload string too long

mysql - 单表特定单元格之间的SQL计算