Redis vs MySQL 总结
MySQL |
Redis |
INSERT | SET / HSET |
SELECT | GET / HGET / HGETALL |
UPDATE | SET / HSET |
DELETE | DEL / HDEL |
SELECT * WHERE id IN (...) | MGET |
SHOW TABLES | KEYS * / SCAN |
BEGIN ... COMMIT | MULTI ... EXEC |
USE DATABASE | SELECT n |
1. 插入数据(INSERT)
MySQL: INSERT INTO users (id, name, age) VALUES (1, 'Alice', 25);
Redis:
SET user:1:name "Alice"
SET user:1:age 25
2. 查询数据(SELECT)
MySQL: SELECT name FROM users WHERE id = 1;
Redis:
GET user:1:name
3. 更新数据(UPDATE)
MySQL: UPDATE users SET age = 26 WHERE id = 1;
Redis:
SET user:1:age 26
4. 删除数据(DELETE)
MySQL: DELETE FROM users WHERE id = 1;
Redis:
DEL user:1:name
DEL user:1:age
5. 设定过期时间
MySQL: DELETE FROM sessions WHERE expire_time < NOW();
Redis:
SET session:123 "user1" EX 3600
EXPIRE session:123 3600
6. 计数操作
MySQL: UPDATE users SET login_count = login_count + 1 WHERE id = 1;
Redis:
INCR user:1:login_count
7. 查询多个数据
MySQL: SELECT * FROM users WHERE id IN (1, 2, 3);
Redis:
MGET user:1:name user:2:name user:3:name
8. 列出所有键
MySQL: SHOW TABLES;
Redis:
KEYS * # 不推荐生产使用
SCAN 0 MATCH user:*
9. 事务
MySQL:
BEGIN;
UPDATE users SET balance = balance - 100 WHERE id = 1;
UPDATE users SET balance = balance + 100 WHERE id = 2;
COMMIT;
Redis:
MULTI
DECRBY user:1:balance 100
INCRBY user:2:balance 100
EXEC
10. 数据库切换
MySQL: USE my_database;
Redis:
SELECT 0 # 选择数据库 0
SELECT 1 # 选择数据库 1