【问题标题】:MySQL: How to use IF condition for ORDER [duplicate]MySQL:如何对 ORDER 使用 IF 条件 [重复]
【发布时间】:2012-04-30 12:30:14
【问题描述】:

可能重复:
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('创建日期' = '创建日期',按 p.created_on DESC 排序, 由 p 订购。在第 17 行

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

然后ORDER BY p.created_on DESC

否则ORDER BY p.created_on ASC

【问题讨论】:

  • 在这里找到了答案:stackoverflow.com/questions/3550942/…
  • 您的问题模棱两可,我的印象是您在问如何动态排序方向,正如我们从您的问题中看到的那样,条件的真假都与 created_on 匹配,它们仅在排序方向(DESC vs ASC)。下一次,让你的问题没有歧义

标签: php mysql sql


【解决方案1】:

使用这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-17
    • 2018-08-16
    • 2016-03-08
    • 1970-01-01
    相关资源
    最近更新 更多