redis一对多的实现???求解
PHP中文网
PHP中文网 2017-04-22 09:00:29
0
4
1641

最近在学习使用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数据设计???

PHP中文网
PHP中文网

认证0级讲师

reply all(4)
PHPzhong

Redis was not designed to handle "relations" from the beginning, and MySQL is a relational database. Although not recommended, it can also be implemented with redis. You can use the user's id as a key and save these images into a list:
$redis->rPush("user_1", "./1zxcz12ad.jpg");
$redis->rPush("user_1", "./zsad12sad.jpg");
$redis->rPush("user_2", "./12eaxx12sw1212.jpg");
Then you can get this list through: $redis->lRange('user_1', 0, -1);.

洪涛

You can only use hash.

Ty80

The user main table uses hash.
The pics table is also processed using hash, but the field uses the ID of the pics

Peter_Zhu

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'}"

Applicable to 1-to-many or 1-to-1 (ZADD key score member):

ZADD User_Pics 1 1
ZADD User_Pics 1 2
ZADD User_Pics 2 4

Query user 2’s pics (ZRANGEBYSCORE key min max [WITHSCORES])

ZRANGEBYSCORE User_Pics 2 2

Query the pics of user 1 and 2

ZRANGEBYSCORE User_Pics 1 2 WITHSCORES

Query the user (ZSCORE key member) of pics 4

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]'}"

For many-to-many (value is "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 "

Query user 2’s pics

ZRANGEBYSCORE User_Pics 2 2

Query the pics of user 1 and 2

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"

Query the user of pics1 1

ZRANGEBYSCORE Pics_User 1 1

Query the user of pics1 1 and 2

ZRANGEBYSCORE Pics_User 1 2 WITHSCORES

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!