Redis vs MySQL 数据类型总结

Redis数据类型 MySQL 类比 适用场景
String VARCHAR/TEXT 或 INT 配置信息、计数器、缓存
Hash 表中的一行数据 用户信息、订单信息
List ORDER BY 排序的记录 消息队列、评论列表
Set DISTINCT 关键字查询 标签、关注/粉丝列表
Sorted Set ORDER BY 排行榜、时间队列
Bitmap TINYINT(1) 活跃用户、签到统计
HyperLogLog COUNT(DISTINCT column) 统计 UV/DAU

1. String(字符串)

MySQL:
CREATE TABLE users (
    id INT PRIMARY KEY,
    name VARCHAR(255),
    age INT
);
INSERT INTO users (id, name, age) VALUES (1, 'Alice', 25);
SELECT name FROM users WHERE id = 1;

Redis:
SET user:1:name "Alice"
SET user:1:age 25
GET user:1:name
GET user:1:age
    

2. Hash(哈希表)

MySQL:
CREATE TABLE users (
    id INT PRIMARY KEY,
    name VARCHAR(255),
    age INT
);
INSERT INTO users (id, name, age) VALUES (1, 'Alice', 25);
SELECT name FROM users WHERE id = 1;

Redis:
HSET user:1 name "Alice" age 25
HGET user:1 name
HGETALL user:1
    

3. List(列表)

MySQL:
CREATE TABLE messages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT,
    message TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO messages (user_id, message) VALUES (1, 'Hello'), (1, 'How are you?');
SELECT message FROM messages WHERE user_id = 1 ORDER BY created_at DESC LIMIT 1;

Redis:
LPUSH messages:1 "Hello" "How are you?"
LRANGE messages:1 0 -1
LPOP messages:1
    

4. Set(集合)

MySQL:
CREATE TABLE tags (
    user_id INT,
    tag VARCHAR(50),
    PRIMARY KEY (user_id, tag)
);
INSERT INTO tags (user_id, tag) VALUES (1, 'redis'), (1, 'mysql');
SELECT DISTINCT tag FROM tags WHERE user_id = 1;

Redis:
SADD user:1:tags "redis" "mysql"
SMEMBERS user:1:tags
SISMEMBER user:1:tags "redis"
    

5. Sorted Set(有序集合)

MySQL:
CREATE TABLE leaderboard (
    user_id INT PRIMARY KEY,
    score INT
);
INSERT INTO leaderboard (user_id, score) VALUES (1, 100), (2, 200);
SELECT * FROM leaderboard ORDER BY score DESC LIMIT 1;

Redis:
ZADD leaderboard 100 user1
ZADD leaderboard 200 user2
ZRANGE leaderboard 0 -1 WITHSCORES
ZREVRANGE leaderboard 0 -1 WITHSCORES
    

6. Bitmap(位图)

MySQL:
CREATE TABLE user_activity (
    user_id INT PRIMARY KEY,
    is_active BOOLEAN
);
INSERT INTO user_activity (user_id, is_active) VALUES (1, 1);
SELECT is_active FROM user_activity WHERE user_id = 1;

Redis:
SETBIT user:activity 1 1
GETBIT user:activity 1
    

7. HyperLogLog(基数统计)

MySQL:
SELECT COUNT(DISTINCT ip) FROM visits;

Redis:
PFADD unique_ips "192.168.1.1" "192.168.1.2"
PFCOUNT unique_ips