我有以下查询,可能需要很长时间。
SELECT b.*, ubh.bookId, ubh.position, ubh.completedDate, ubh.userId
FROM user_book_history AS ubh
INNER JOIN books AS b ON ubh.bookId = b.id
WHERE ubh.userId = ? ORDER by ubh.createDate desc
我可以做什么来优化这个查询?我应该向 mysql 表添加哪些索引?有人可以帮忙吗?
CREATE TABLE "user_book_history" (
"id" int NOT NULL AUTO_INCREMENT,
"bookId" int DEFAULT NULL,
"userId" int DEFAULT NULL,
"position" int DEFAULT '0',
"createDate" bigint DEFAULT NULL,
"completedDate" bigint DEFAULT NULL,
PRIMARY KEY ("id")
);
CREATE TABLE "books" (
"id" int NOT NULL AUTO_INCREMENT,
"amazonBuyUrl" text,
"audioUrl" varchar(255) DEFAULT NULL,
"author" varchar(255) DEFAULT NULL,
"authorDesc" text,
"body" longtext,
"categories" varchar(255) DEFAULT NULL,
"description" text,
"image" text,
"publishDate" bigint DEFAULT NULL,
"subtitle" varchar(255) DEFAULT NULL,
"title" varchar(255) DEFAULT NULL,
"uploadDate" bigint DEFAULT NULL,
"video" varchar(255) DEFAULT NULL,
"mediaUrl" varchar(255) DEFAULT NULL,
"subid" varchar(255) DEFAULT NULL,
"tags" varchar(255) DEFAULT NULL,
"free" tinyint DEFAULT '0',
"infographicUrl" varchar(255) DEFAULT NULL,
"vector" varchar(255) DEFAULT NULL,
"comingSoon" tinyint DEFAULT '0',
"isPopular" tinyint DEFAULT NULL,
PRIMARY KEY ("id")
);
我附上了 EXPLAIN 输出和创建表
这应该优化特定
userId
的查找、按 createDate
排序以及对连接的 bookId
的引用:
ALTER TABLE user_book_history
ADD INDEX (userId, createDate);
这并没有实现覆盖索引优化,因为您的查询引用了其他列。
books.id
是该表的主键。您的解释显示该连接已经作为 eq_ref 访问进行了优化。您无需对该表执行任何其他操作。