4. 对list进行sort

一. sort命令

  1. sort命令可以对list排序
  2. sort命令把字段转先换为double类型在进行比较
  3. sort排序list
127.0.0.1:6379> lrange list2 0 -1
1) "f"
2) "c"
3) "e"
4) "a"
5) "b"
127.0.0.1:6379> sort list2
(error) ERR One or more scores canot be converted into double
127.0.0.1:6379> sort list2 alpha   # sort默认至排序double,排序字母需要生命alpha
1) "a"
2) "b"
3) "c"
4) "e"
5) "f"
127.0.0.1:6379> lrange shuzi 0 -1
1) "2"
2) "7"
3) "21"
4) "4"
5) "3"
6) "1"
127.0.0.1:6379> sort shuzi asc
1) "1"
2) "2"
3) "3"
4) "4"
5) "7"
6) "21"
127.0.0.1:6379> sort shuzi limit 0 2    #从0开始取2个元素
1) "1"
2) "2"
127.0.0.1:6379> lpush list1 4 2 3 1
127.0.0.1:6379> lrange list1 0 -1
1) "1"
2) "3"
3) "2"
4) "4"
127.0.0.1:6379> sort list1 store list2   #sort不会改变原先list的元素位置
127.0.0.1:6379> lrange list1 0 -1
1) "1"
2) "3"
3) "2"
4) "4"
127.0.0.1:6379> lrange list2 0 -1
1) "1"
2) "2"
3) "3"
4) "4"

二. string作参考键的排序

zset用每个元素的分数进行排序,而排序list,就用list中每个元素对应的参考键的值作为分数进行排序
[注]:list一般存储的元素是id,id排序没有意义,如下id对应的score排序才有意义,
sort list by key 转化为sql==> select id from list order by key

127.0.0.1:6379> lpush list1 3 2 4 1
127.0.0.1:6379>  lrange list1 0 -1
1) "1"
2) "4"
3) "2"
4) "3"
127.0.0.1:6379> set score_1 90
127.0.0.1:6379> set score_2 85
127.0.0.1:6379> set score_3 -10
127.0.0.1:6379> sort list1 by score_*    # 不存在的参考件对应的id默认值为0
1) "3"
2) "4"
3) "2"
4) "1"

三. 用hash作参考键

127.0.0.1:6379> hset post_1 title one
127.0.0.1:6379> hset post_1 modifytime 123
127.0.0.1:6379> hset post_2 title two
127.0.0.1:6379> hset post_2 modifytime 234
127.0.0.1:6379> hset post_3 title three
127.0.0.1:6379> hset post_3 modifytime 99
127.0.0.1:6379> lrange list1 0 -1
1) "1"
2) "4"
3) "2"
4) "3"
127.0.0.1:6379> sort list1 by post_*->modifytime     #用post_*的modufytime作为参考键
1) "4"    #0
2) "3"    #99
3) "1"    #123
4) "2"    #234
127.0.0.1:6379> sort list1 by post_*->modifytime get # get post_*->title    # get表示获取的字段,get #获取list1的元素,
# select id,title order by modifytime
1) "4"          
2) (nil)
3) "3"
4) "three"
5) "1"
6) "one"
7) "2"
8) "two"
原文地址:https://www.cnblogs.com/72808ljup/p/5208475.html