最近在學習使用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數據設計???
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。
只能用hash了。
user主表用hash來做。
pics從表格同樣用hash來做,只是field用pics的ID
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'}"
HSETs 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"
DD User_Pics 2 "2-1 "
查詢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