MySQL按两列排序,按字母顺序排序剩余记录

时间:2015-07-23 17:04:45

标签: mysql sorting multiple-columns

我的MySQL表中有三列三列:

title, featured, sort_order

其中titlevarcharfeaturedenum("是"或"否")和{{1是} sort_order

我想将结果集返回到" YES"首先,然后将特色排序为"是"以int升序(0,1,2,3等等),然后按sort_order(字母顺序)对剩余记录进行排序。

我在title ASC等处查看,但我找不到答案。

希望我想要完成的事情是有道理的。任何帮助将不胜感激:)

4 个答案:

答案 0 :(得分:1)

你是说这个?

select *, IF(featured = 'YES', 0, 1) AS ftsort, CAST(IF(featured = 'YES', sort_oder, title) AS CHAR) AS nosort 
from table
order by ftsort ASC, nosort ASC 

答案 1 :(得分:0)

GROUP BY会影响您获得的结果集,这是您不想要的结果:在以特定方式对返回值进行排序时,您需要使用ORDER BY:

SELECT FEATURED, SORT_ORDER, TITLE FROM your_table
ORDER BY FEATURED, TITLE ASC, SORT_ORDER

答案 2 :(得分:0)

与DiscipleMichael提到的一样,您不能使用UNION SELECT使用ORDER BY子句。但是有一种解决方法,您可以将有序查询包装在子选择中。

我将如何做到这一点:

SELECT * FROM (SELECT title, featured FROM yourTable WHERE featured = 'YES' ORDER BY sort_order) AS featuredYES
UNION
SELECT * FROM (SELECT title, featured FROM yourTable WHERE featured = 'NO' ORDER BY title) AS featuredNO 

这可能比弄乱if s:

更好
  • 更具可读性;
  • 它允许您在需要时轻松添加其他订单序列;
  • 它允许您根据需要混合ASCDESC订单序列。

答案 3 :(得分:0)

将下面的sql转换为MySQL(需要的地方),这样就可以了。

DECLARE @myTable as Table
(
    title varchar(50),
    featured varchar(3),
    sort_order int
)

Insert INTO @myTable
    SELECT title, featured, sort_order
    FROM test1
    WHERE featured = 'YES'
    ORDER BY sort_order

Insert INTO @myTable
    SELECT title, featured, sort_order
    FROM test1
    WHERE featured = 'NO'
    ORDER BY title ASC

SELECT * FROM @myTable

我相信下面的MySQL版本是正确的(请验证)。

Create TEMPORARY TABLE myTable 
(
    title varchar(50),
    featured varchar(3),
    sort_order int
);

Insert INTO myTable
    (SELECT title, featured, sort_order
    FROM test1
    WHERE featured = 'YES'
    ORDER BY sort_order);

Insert INTO myTable
    (SELECT title, featured, sort_order
    FROM test1
    WHERE featured = 'NO'
    ORDER BY title ASC);

SELECT * FROM myTable

当然,我的字段类型可能与您的不同,只需将create语句修改为正确的类型即可。