我有下表。 email / sites_id上的唯一索引是否足以使SELECT * FROM users WHERE fk=123 AND email="john@example.com";
等查询针对检索进行优化?
CREATE TABLE IF NOT EXISTS `users` (
`id` INT UNSIGNED NOT NULL,
`name` VARCHAR(45) NOT NULL,
`email` VARCHAR(45) NULL,
`fk` INT UNSIGNED NULL,
`sites_id` INT UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `unique_email` (`email` ASC, `sites_id` ASC),
INDEX `fk_index` (`fk` ASC),
INDEX `fk_sites_index` (`sites_id` ASC),
CONSTRAINT `fk_constraint`
FOREIGN KEY (`fk`)
REFERENCES `other_table` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `sites_constraint`
FOREIGN KEY (`sites_id`)
REFERENCES `sites` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
PACK_KEYS = 0
ROW_FORMAT = DEFAULT;
答案 0 :(得分:0)
对于此查询:
SELECT *
FROM users
WHERE fk = 123 AND email = 'john@example.com';
users(fk, email)
或users(email, fk)
上的最佳索引,或以这两列开头的任何索引。对于检索性能,唯一索引和非唯一索引之间的差异介于空白和可忽略不计之间。
我没有碰巧在你的索引列表中看到它,所以你应该添加它。
注意:查询可以(可能)使用unique_email
或fk_index
,但最佳索引是从这两列开始的复合索引(按任意顺序)。