最近在学习使用redis,在关系型的mysql下一个简单的一对多,很简单,如下
用户表user主表
id | name | age |
---|---|---|
1 | jack | 5 |
2 | rose | 12 |
3 | dad | 23 |
图片表pics从表
id | uid | img_url |
---|---|---|
1 | 1 | ./1zxcz12ad.jpg |
2 | 1 | ./zsad12sad.jpg |
3 | 1 | ./12ea2222123xsw1212.jpg |
4 | 2 | ./12eaxx12sw1212.jpg |
换到基于key=》value的redis就晕了。。。请问如何设计出符合上表格的redis数据设计???
PHPz2017-04-22 09:02:29
redis设计之初就不是为了处理“关系”的,而mysql就是关系型数据库。虽然不建议,但是redis也可以实现。你可以用用户的id作健,把这些image存进一个list中:
$redis->rPush("user_1", "./1zxcz12ad.jpg");
$redis->rPush("user_1", "./zsad12sad.jpg");
$redis->rPush("user_2", "./12eaxx12sw1212.jpg");
然后可以通过:$redis->lRange('user_1', 0, -1);取到这个list。
天蓬老师2017-04-22 09:02:29
HSET User 1 "{name: 'jack', age: 5, Pics: [1, 2]}"
HSET User 2 "{name: 'rose', age: 12, Pics: [4]}"
HSET Pics 1 "{img_url: './1zxcz12ad.jpg', User: 1'}"
HSET Pics 2 "{img_url: './zsad12sad.jpg', User: 1'}"
HSET Pics 4 "{img_url: './12eaxx12sw1212.jpg', User: 2'}"
适用于1对多或者1对1 (ZADD key score member):
ZADD User_Pics 1 1
ZADD User_Pics 1 2
ZADD User_Pics 2 4
查询user 2的pics (ZRANGEBYSCORE key min max [WITHSCORES])
ZRANGEBYSCORE User_Pics 2 2
查询user 1和2的pics
ZRANGEBYSCORE User_Pics 1 2 WITHSCORES
查询pics 4的user (ZSCORE key member)
ZSCORE User_Pics 4
HSET User 1 "{name: 'jack', age: 5, Pics: [1, 2]}"
HSET User 2 "{name: 'rose', age: 12, Pics: [1,2]}"
HSET Pics 1 "{img_url: './1zxcz12ad.jpg', User: [1, 2]'}"
HSET Pics 2 "{img_url: './zsad12sad.jpg', User: [1, 2]'}"
对于多对多 (值为 "userID-PicsID" ):
ZADD User_Pics 1 "1-1"
ZADD User_Pics 1 "1-2"
ZADD User_Pics 2 "2-1"
ZADD User_Pics 2 "2-2"
查询user 2的pics
ZRANGEBYSCORE User_Pics 2 2
查询user 1和2的pics
ZRANGEBYSCORE User_Pics 1 2 WITHSCORES
ZADD Pics_User 1 "1-1"
ZADD Pics_User 1 "2-1"
ZADD Pics_User 2 "1-2"
ZADD Pics_User 2 "2-2"
查询pics1 1的user
ZRANGEBYSCORE Pics_User 1 1
查询pics1 1和2的user
ZRANGEBYSCORE Pics_User 1 2 WITHSCORES