-- 1. 使用函数导致索引失效SELECT * FROM users WHERE YEAR(birthday) = 1990; -- 索引失效-- 2. 隐式类型转换SELECT * FROM users WHERE user_id = '123'; -- 如果user_id是int类型,可能导致索引失效-- 3. 使用不等于或不包含SELECT * FROM users WHERE name != '张三'; -- 可能导致索引失效-- 4. 使用OR连接条件SELECT * FROM users WHERE name = '张三' OR age = 25; -- 如果age没有索引,整个查询可能放弃使用索引
CREATE TABLE orders ( id BIGINT PRIMARY KEY, user_id BIGINT NOT NULL, order_status TINYINT NOT NULL, create_time DATETIME NOT NULL, payment_time DATETIME, ...);
常见查询与索引设计:
-- 用户查询自己的订单,按创建时间倒序CREATE INDEX idx_user_create ON orders(user_id, create_time);-- 后台按订单状态和创建时间查询CREATE INDEX idx_status_create ON orders(order_status, create_time);
CREATE TABLE user_relations ( id BIGINT PRIMARY KEY, user_id BIGINT NOT NULL, follow_user_id BIGINT NOT NULL, relation_type TINYINT NOT NULL, create_time DATETIME NOT NULL);-- 查询用户的关注列表CREATE INDEX idx_user_relation_time ON user_relations(user_id, relation_type, create_time);-- 查询用户的粉丝列表CREATE INDEX idx_follow_relation_time ON user_relations(follow_user_id, relation_type, create_time);