MySQL分层的IF语句

时间:2013-01-04 04:57:20

标签: mysql if-statement sql-order-by

我正在尝试完成这段代码:

ORDER BY IF(j.groups IS NULL OR j.groups = '',  IF(j.title IS NULL, i.title), j.groups)

在英语中:如果j.groups存在,则首先按顺序排序,然后按j.title排序,如果它是eixsts,最后是i.title。但上述情况并未奏效。

2 个答案:

答案 0 :(得分:1)

试试这个:

ORDER BY IF(j.groups IS NULL OR j.groups = '', IFNULL(j.title, i.title), j.groups);

ORDER BY COALESCE(j.groups, j.title, i.title);

ORDER BY IF(j.groups IS NULL OR j.groups = '', IF(j.title IS NULL, i.title, 1), j.groups);

答案 1 :(得分:0)

您忘记了内部IF else 部分。试试这个:

ORDER BY IF(
  j.groups IS NULL OR j.groups = '',
  IF(
    j.title IS NULL,
    i.title,
    j.title -- this was missing
  ),
  j.groups
)

但我发现这种语法更具可读性:

ORDER BY COALESCE(IF(j.groups = '', NULL, j.groups), j.title, i.title)