2016-08-09 8 views
3

私は特別な並べ替えをmysqlデータベースのテーブルレコードの下に作成したいと思いますので、最初の行の赤、2番目の行の緑、3番目の行の赤、4番目の行の緑、ので、私は彼らが、これはMySQLの順序を使用して達成することができる方法をMysqlの特別な代替ソート

、赤、緑、赤、緑、赤、...

としてソートすることがしたいですか?テストの目的のためのMySQLのテーブルの下

CREATE TABLE `fav_color` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, 
    `color` enum('red','green') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'red', 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ; 

INSERT INTO `fav_color` (`id`, `name`, `color`) VALUES 
    (1, 'test', 'red'), 
    (2, 'testing 33', 'red'), 
    (3, 'test 444', 'green'), 
    (4, 'test 555', 'red'), 
    (5, 'test 6666', 'green'), 
    (6, 'test 7777', 'red'), 
    (7, 'test 8888', 'red'), 
    (8, 'test 9999', 'red'), 
    (9, 'test 1000', 'green'), 
    (10, 'test 11111', 'green'), 
    (11, 'test 122222', 'green'), 
    (12, 'test 13333333', 'green'); 

おかげで、

答えて

1

これはトリッキーです。一つの方法は、各色の値を列挙し、次に列挙することにより、集約することです:

select c.* 
from (select c.*, 
      (@rn := if(@c = color, @rn + 1, 
         if(@c := color, 1, 1) 
         ) 
      ) as rn 
     from fav_color c cross join 
      (select @c := '', @rn := 0) params 
     order by c.color, c.id 
    ) c 
order by rn, field(color, 'red', 'green'); 
2

あなたは、奇数と偶数行の行番号とcahnge順序を取得し、色で並べ替えることができます。

select * from (
    select @rownum := @rownum + 1 AS rank, fav_color.* 
    from fav_color cross join (select @rownum := 0) t 
    order by color, id 
) t 
order by 
    -- Here @rownum is equal to count of records of subquery 
    (1 - rank % 2) * (@rownum + @rownum % 2 - rank + 1) + -- even 
    (rank % 2) * rank, -- odd 
    color 
0

あなたが奇数と 偶数行の行番号とcahnge順序を取得し、色で並べ替えることができます[おかげmnv]

set @rownum := 0; 
select * from (select @rownum := @rownum + 1 AS sort_col_fld, fav_color.* 
    from fav_color order by color, id) as tmp_table_alias 
order by 
    -- Here @rownum is equal to count of records of subquery 
    (1 - sort_col_fld % 2) * (@rownum + @rownum % 2 - sort_col_fld + 1) + -- Even 
    (sort_col_fld % 2) * sort_col_fld -- Odd 
    , color