书签系统
create table book (
bookid int,
title char(20),
)engine myisam charset utf8;
insert into book values
(5 , 'PHP圣经'),
(6 , 'ruby实战'),
(7 , 'mysql运维')
(8, 'ruby服务端编程');
create table tags (
tid int,
bookid int,
content char(20)
)engine innodb charset utf8;
insert into tags values
(10 , 5 , 'PHP'),
(11 , 5 , 'WEB'),
(12 , 6 , 'WEB'),
(13 , 6 , 'ruby'),
(14 , 7 , 'database'),
(15 , 8 , 'ruby'),
(16 , 8 , 'server');
# 既有web标签,又有PHP ,要用连接查询
select * from tags inner join tags as t on tags.bookid=t.bookid where tags.content='PHP' and t.content='WEB';
mysql> select * from tags inner join tags as t on tags.bookid=t.bookid
-> where tags.content='PHP' and t.content='WEB';
+------+--------+---------+------+--------+---------+
| tid | bookid | content | tid | bookid | content |
+------+--------+---------+------+--------+---------+
| 10 | 5 | PHP | 11 | 5 | WEB |
+------+--------+---------+------+--------+---------+
1 row in set (0.00 sec)
mysql> select t1.bookid from tags as t1 inner join tags as t2 on t1.bookid=t2.bookid where t1.content='PHP' and t2.content='WEB';
+--------+
| bookid |
+--------+
| 5 |
+--------+
1 row in set (0.00 sec)
换成key-value存储
用kv 来存储
set book:5:title 'PHP圣经'
set book:6:title 'ruby实战'
set book:7:title 'mysql运难'
set book:8:title ‘ruby server’
sadd tag:PHP 5
sadd tag:WEB 5 6
sadd tag:database 7
sadd tag:ruby 6 8
sadd tag:SERVER 8
查: 既有PHP,又有WEB的书
Sinter tag:PHP tag:WEB #查集合的交集
查: 有PHP或有WEB标签的书
Sunin tag:PHP tag:WEB
查:含有ruby,不含WEB标签的书
Sdiff tag:ruby tag:WEB #求差集
Redis key 设计技巧
1: 把表名转换为key前缀 如, tag:
2: 第2段放置用于区分key的字段---对应mysql中的主键的列名,如userid
3: 第3段放置主键值,如2,3,4...., a , b ,c
4: 第4段,写要存储的列名
用户表 user , 转换为key-value存储 |
|||
userid |
username |
passworde |
|
9 |
Lisi |
1111111 |
lisi@163.com |
set user:userid:9:username lisi
set user:userid:9:password 111111
set user:userid:9:email lisi@163.com
keys user:userid:9*
备注:分布式存储时,有个好处,memcache讲过无底洞,这里如此设计key的方式有个好处就是只对前面user:userid:9的内容hash,这样会把所有userid是9的信息同时同步到一台机器上(这样解决了分布式存储时userid是9的信息分散的存储在各个机器上的情况)。
注意:
在关系型数据中,除主键外,还有可能其他列也步骤查询,
如上表中, username 也是极频繁查询的,往往这种列也是加了索引的.
转换到k-v数据中,则也要相应的生成一条按照该列为主的key-value
set user:username:lisi:uid 9
这样,我们可以根据username:lisi:uid ,查出userid=9,
再查user:9:password/email ...
综上:完成了根据用户名来查询用户信息