0

settings我在表中有 order by 设置,我想order by使用此选项进行更改,在下面的 sql 命令中,如果sortable字段 intosettings为 1,则 order by 必须为ORDER BY DATE,如果sortable为 2,则 order by 必须为ORDER BY ID。请帮我有正确的sql命令

MYSQL:

SELECT 
      SQL_CALC_FOUND_ROWS i.* , 
                     c.title AS category_name, 
                     u.name, 
                     u.family, 
                     s.title AS status_title, 
                     i.thumb_image,
                     CONCAT( u.name, ' ', u.family ) AS author
      FROM   contents i
      JOIN   categories c ON c.id = i.category
      JOIN   users u ON u.id = i.posted_by
      JOIN   status_topics s ON s.id = i.t_status
      WHERE 
      i.portal = 0
              AND (CASE WHEN post_type = 4
                    THEN date(NOW()) BETWEEN i.from_dateTime AND i.to_dateTime 
                   ELSE post_type = 1
                   END)

                  (select sortable from settings) 
                  (case when sortable = 1 then 
                                 ORDER BY topic_date
                  case when sortable = 2 then 
                                 ORDER BY id
                  case when sortable = 3 then 
                                 ORDER BY public
                  end)

                  LIMIT 10
4

1 回答 1

3

根据与 OP 的讨论,注意答案略有变化。

ORDER BY 外面CASE, 像这样:

... the first part of the query, then ...
ORDER BY
  CASE (SELECT sortable FROM settings)
    WHEN 1 THEN topic_date
    WHEN 2 THEN id
    WHEN 3 THEN public
  END
LIMIT 10

请注意,这仅在(SELECT sortable FROM settings)返回一行时才有效。如果它返回多于一行,则会出现错误。如果它返回零行,则不会出现错误,但不会选择任何排序选项 - 这与说ORDER BY NULL.

于 2013-06-12T15:16:17.543 回答