I have the following three WHERE
clauses:
WHERE primaryId = $imgId AND imgWidth = $maxImageWidth AND imgHeight = $maxImageHeight
WHERE primaryId = $imgId AND imgWidth = $maxImageWidth AND imgHeight != $maxImageHeight
WHERE primaryId = $imgId AND imgWidth != $maxImageWidth AND imgHeight = $maxImageHeight"
They are acting upon two MySQL InnoDB tables joined in the query with UNION ALL
.
I am not sure how I should set up the Indexes in these two tables; Whether I should have a Multi-Column Index, with imgWidth
and imgHeight
, or if it should include primaryId
as well?
Is it true that a query can only use one index? If not, could I set up each column as an index?
Or would a Multi-Column Index not work in this case?
Here is an example of the entire query for the first WHERE
clause. The others are the same, with the respective clauses:
SELECT 'allEqual' AS COL1,COUNT(*) AS imgCount FROM (
SELECT imgHeight, imgWidth, imgId AS primaryId FROM primary_images
UNION ALL
SELECT imgHeight, imgWidth, primaryId FROM secondary_images
) AS union_table
WHERE primaryId = $imgId AND imgWidth = $maxImageWidth AND imgHeight = $maxImageHeight
Here is the schema of the primary_images
table:
CREATE TABLE IF NOT EXISTS `new_arrivals_images`.`primary_images` (
`imgId` SMALLINT(6) UNSIGNED NOT NULL AUTO_INCREMENT ,
`imgTitle` VARCHAR(255) NULL DEFAULT NULL ,
`view` VARCHAR(45) NULL DEFAULT NULL ,
`secondary` ENUM('true','false') NOT NULL DEFAULT false ,
`imgURL` VARCHAR(255) NULL DEFAULT NULL ,
`imgWidth` SMALLINT(6) UNSIGNED NULL DEFAULT NULL ,
`imgHeight` SMALLINT(6) UNSIGNED NULL DEFAULT NULL ,
`imgDate` DATETIME NULL DEFAULT NULL ,
`imgClass` ENUM('Jeans','T-Shirts','Shoes','Dress Shirts','Trackwear & Sweatwear') NULL DEFAULT NULL ,
`imgFamily` ENUM('Hugo Boss','Lacoste','True Religion','7 For All Mankind','Robin\'s Jeans','Robert Graham') NULL DEFAULT NULL ,
`imgGender` ENUM('Men\'s','Women\'s') NOT NULL DEFAULT Mens ,
PRIMARY KEY (`imgId`) ,
UNIQUE INDEX `imgDate_UNIQUE` (`imgDate` DESC) )
ENGINE = InnoDB;
And the schema for the secondary_images
table:
CREATE TABLE IF NOT EXISTS `new_arrivals_images`.`secondary_images` (
`imgId` SMALLINT(6) UNSIGNED NOT NULL AUTO_INCREMENT ,
`primaryId` SMALLINT(6) UNSIGNED NOT NULL ,
`view` VARCHAR(45) NULL DEFAULT NULL ,
`imgURL` VARCHAR(255) NULL DEFAULT NULL ,
`imgWidth` SMALLINT(6) UNSIGNED NULL DEFAULT NULL ,
`imgHeight` SMALLINT(6) UNSIGNED NULL DEFAULT NULL ,
`imgDate` DATETIME NULL DEFAULT NULL ,
PRIMARY KEY (`imgId`, `primaryId`) ,
INDEX `fk_secondary_images_primary_images` (`primaryId` ASC) ,
UNIQUE INDEX `imgDate_UNIQUE` (`imgDate` DESC) ,
CONSTRAINT `fk_secondary_images_primary_images`
FOREIGN KEY (`primaryId` )
REFERENCES `new_arrivals_images`.`primary_images` (`imgId` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;