鍍金池/ 問(wèn)答/數(shù)據(jù)庫(kù)/ mysql如何根據(jù)某個(gè)字段的值進(jìn)行循環(huán)排序?

mysql如何根據(jù)某個(gè)字段的值進(jìn)行循環(huán)排序?

表 T1 中有若干數(shù)據(jù),有字段 C1 用于數(shù)據(jù)分類,請(qǐng)問(wèn)是否能在 SELECT 中返回按照 C1 的循環(huán)分類排序?

假設(shè) C1 字段有三種數(shù)據(jù),分別是”類1“,”類2“,”類3“,期待結(jié)果如下:
如 '類1'數(shù)據(jù)已排完,則類2 類3 補(bǔ)上一次排序
C1

類1,數(shù)據(jù)。。。
類2,數(shù)據(jù)。。。。
類3,數(shù)據(jù)。。。
類1,數(shù)據(jù)。。。
類2,數(shù)據(jù)。。
類3,數(shù)據(jù)。。。。
類1,數(shù)據(jù)。。。。。。

回答
編輯回答
慢半拍

不是很明白你的需求,可能 mysql 能實(shí)現(xiàn),但不推薦使用 mysql 處理,不知道你的方向是程序還是 DBA ,如果是程序的話建議程序處理。因?yàn)閿?shù)據(jù)庫(kù)的話是共用的,你如果在數(shù)據(jù)庫(kù)中進(jìn)行操作,將會(huì)消耗數(shù)據(jù)庫(kù)的性能,導(dǎo)致堵塞情況出現(xiàn)是很不好的。

2017年6月14日 17:00
編輯回答
伴謊

作者:飛鳥
鏈接:https://www.zhihu.com/questio...
來(lái)源:知乎

mysql> select * from t limit 10;
id c
521 group2
522 group2
523 group3
524 group2
525 group3
526 group2
527 group2
528 group3
529 group2
530 group1

10 rows in set (0.00 sec)

mysql> select c,count(*) from t group by c;
c count(*)
group1 13
group2 19
group3 28

3 rows in set (0.00 sec)

mysql> select c,id from t ,(select @x:=0,@y:=0,@z:=0) x order by
    -> case when c='group1' then @x:=@x+1
    -> when c='group2' then @y:=@y+1
    -> when c='group3' then @z:=@z+1 end
    ->  ,c limit 20;
c id
group1 530
group2 521
group3 523
group1 532
group2 522
group3 525
group1 535
group2 524
group3 528
group1 540
group2 526
group3 533
group1 541
group2 527
group3 538
group1 545
group2 529
group3 539
group1 547
group2 531

20 rows in set (0.00 sec)

思路大體是,列出表T,如果group2第一次出現(xiàn),則這一行標(biāo)記為grp=1,第二次出現(xiàn),標(biāo)記為grp=2,第n次出現(xiàn)則標(biāo)記為grp=n……group1和group3也同樣處理,然后按照grp 和c 排序即可。

2018年7月8日 19:31
編輯回答
使勁操

應(yīng)該實(shí)現(xiàn)不了吧,要不直接加一列作為排序列,手動(dòng)搞?

2018年6月16日 14:57
編輯回答
笨小蛋

按道理使用mysql來(lái)處理這種邏輯不適合,建議在代碼層上進(jìn)行處理

2018年4月28日 20:36