redis 交集、并集、差集

文章目录

一、sinter 、sunion 、sdiff

redis 支持 Set集合的数据存储,其中有三个比较特殊的方法:

  • sinter key [key …] 查看一个集合的全部成员,该集合是所有给定集合的交集。
  • sunion key [key …] 查看一个集合的全部成员,该集合是所有给定集合的并集。
  • sdiff key [key …] 查看所有给定 key 与第一个 key 的差集

1.1、sinter 交集的示例

redis> SMEMBERS group_1
1) "LI LEI"
2) "TOM"
3) "JACK"

redis> SMEMBERS group_2
1) "HAN MEIMEI"
2) "JACK"

redis> SINTER group_1 group_2      # 取的是交集的数据 
1) "JACK"

1.2、sunion 并集的示例

redis> SMEMBERS songs
1) "Billie Jean"

redis> SMEMBERS my_songs
1) "Believe Me"

redis> SUNION songs my_songs       # 取的是集合的并集数据
1) "Billie Jean"
2) "Believe Me"

1.3、sdiff 差集的示例

redis> SMEMBERS peter_movies
1) "bet man"
2) "start war"
3) "2012"

redis> SMEMBERS joe_movies
1) "hi, lady"
2) "Fast Five"
3) "2012"

redis> SDIFF peter_movies joe_movies     # 取的是两个集合的差集
1) "bet man"
2) "start war"

二、sinterstore、sunionstore、sdiffstore

  • sinterstore destination key [key …] 将 交集 数据存储到某个对象中
  • sunionstore destination key [key …] 将 并集 数据存储到某个对象中
  • sdiffstore destination key [key …] 将 差集 数据存储到某个对象中

2.1、sinterstore 交集的示例

redis> SMEMBERS songs
1) "good bye joe"
2) "hello,peter"

redis> SMEMBERS my_songs
1) "good bye joe"
2) "falling"

redis> SINTERSTORE song_interset songs my_songs           # 将交集的数据存储到 song_interset 对象中
(integer) 1

redis> SMEMBERS song_interset                 # 查看 song_interset 对象中的 所有数据
1) "good bye joe"

2.2、sunionstore 并集的示例

redis> SMEMBERS NoSQL
1) "MongoDB"
2) "Redis"

redis> SMEMBERS SQL
1) "sqlite"
2) "MySQL"

redis> SUNIONSTORE db NoSQL SQL      # 将并集的数据存储到 db 对象中
(integer) 4

redis> SMEMBERS db            # 查看 db 对象中的 所有数据
1) "MySQL"
2) "sqlite"
3) "MongoDB"
4) "Redis"

2.3、sdiffstore 差集的示例

redis> SMEMBERS joe_movies
1) "hi, lady"
2) "Fast Five"
3) "2012"

redis> SMEMBERS peter_movies
1) "bet man"
2) "start war"
3) "2012"

redis> SDIFFSTORE joe_diff_peter  joe_movies  peter_movies          # 将差集的数据存储到 joe_diff_peter 对象中
(integer) 2

redis> SMEMBERS joe_diff_peter              # 查看 joe_diff_peter 对象中的 所有数据
1) "hi, lady"
2) "Fast Five"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值