1. 程式人生 > >Redis大總結之三:SORT命令(對 列表|集合|有序集合 進行排序)

Redis大總結之三:SORT命令(對 列表|集合|有序集合 進行排序)

SORT命令

 列表|集合|有序集合 進行排序

對列表進行排序:

127.0.0.1:6379[5]> lrange myList 0 -1

1) "1"

2) "2"

3) "4"

4) "3"

5) "5"

127.0.0.1:6379[5]> sort myList

1) "1"

2) "2"

3) "3"

4) "4"

5) "5"

127.0.0.1:6379[5]> lrange myList 0 -1

1) "1"

2) "2"

3) "4"

4) "3"

5) "5"

對有序集合進行安排續:會忽略有序幾個元素的分數,只針對元素鍵排序,加上alpha引數。

127.0.0.1:6379[5]> zadd set5 30 a 10 b 20 c 5 d

(integer) 4

127.0.0.1:6379[5]> zrange set5 0 -1 withscores

1) "d"

2) "5"

3) "b"

4) "10"

5) "c"

6) "20"

7) "a"

8) "30"

127.0.0.1:6379[5]> sort set5

(error) ERR One or more scores can't be converted into double

127.0.0.1:6379[5]> sort set5 alpha

1) "a"

2) "b"

3) "c"

4) "d"

對集合進行排序:

127.0.0.1:6379[5]> sadd set2 d a c b

(integer) 4

127.0.0.1:6379[5]> smembers set2

1) "c"

2) "a"

3) "b"

4) "d"

127.0.0.1:6379[5]> sort set2

(error) ERR One or more scores can't be converted into double

127.0.0.1:6379[5]> sort set2 alpha

1) "a"

2) "b"

3) "c"

4) "d"

SORT命令之DESC引數:

對列表從大到小排序:

127.0.0.1:6379[5]> lrange myList 0 -1

1) "1"

2) "2"

3) "4"

4) "3"

5) "5"

127.0.0.1:6379[5]> sort myList DESC

1) "5"

2) "4"

3) "3"

4) "2"

5) "1"

對集合從大到小排序:

127.0.0.1:6379[5]> smembers set3

1) "20"

2) "50"

3) "100"

127.0.0.1:6379[5]> sort set3 desc

1) "100"

2) "50"

3) "20"

對有序集合進行排序:

127.0.0.1:6379[5]> zrange set5  0 -1 withscores

1) "d"

2) "5"

3) "b"

4) "10"

5) "c"

6) "20"

7) "a"

8) "30"

127.0.0.1:6379[5]> sort set5 desc

(error) ERR One or more scores can't be converted into double

127.0.0.1:6379[5]> sort set5 alpha desc

1) "d"

2) "c"

3) "b"

4) "a"

SORT命令之LIMIT引數:

127.0.0.1:6379[5]> sort set3 desc

1) "100"

2) "50"

3) "20"

127.0.0.1:6379[5]> sort set3 desc limit 1 2  //向後偏移1個元素,獲取兩個元素

1) "50"

2) "20"

SORT命令之BY,GET引數:

127.0.0.1:6379[6]> lpush list 5 3 9

(integer) 3

127.0.0.1:6379[6]> lrange list 0 -1

1) "9"

2) "3"

3) "5"

127.0.0.1:6379[6]> set it:5 30

OK

127.0.0.1:6379[6]> set it:9 40

OK

127.0.0.1:6379[6]> set it:3 90

OK

127.0.0.1:6379[6]> sort list by it:* desc

1) "3"

2) "9"

3) "5"

127.0.0.1:6379[7]> sort list by it:* desc get it:*//結果顯示it:3,it:9,:it:5對應的值

1) "90"

2) "40"

3) "30"

//解析:如上所示:sortlist列表進行排序,使用了by引數,那麼就不是使用list中的值來排序了,而是將list中的值[9,3,5]替換到[it:*]這個*,替換關係:list[9,3,5]==[it:9,it:3,it:5],然後對[it:9,it:3,it:5]這三個元素排序,以上可知:[it:9,it:3,it:5]對應的值為[it:9=40,it:3=90,it:5=30],倒敘排列對應的關係即為[it:3=90,it:9=40,it:5=30],對應的[it:3=90,it:9=40,it:5=30] == list[3,9,5],即得到list列表的順序。

SORT命令之STORE引數:表示把sort查詢的結果集儲存起來

127.0.0.1:6379[7]> sort list by it:* desc get it:*

1) "90"

2) "50"

3) "40"

127.0.0.1:6379[7]> sort list by it:* desc get it:* store sorc:result//儲存到sorc:result

(integer) 3

127.0.0.1:6379[7]> lrange sorc:result 0 -1

1) "90"

2) "50"

3) "40"

更多:


 ------------------完------------------------