2

The table schema for example:

CREATE TABLE `foos` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `bar1` bigint(20) unsigned NOT NULL,
  `bar2` bigint(20) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uqx_bar1_bar2` (`bar1`,`bar2`),
  KEY `idx_bar1` (`bar1`),
  KEY `idx_bar2` (`bar2`),
  CONSTRAINT `fk_bar1` FOREIGN KEY (`bar1`) REFERENCES `bars1` (`id`),
  CONSTRAINT `fk_bar2` FOREIGN KEY (`bar2`) REFERENCES `bars2` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

This table is created for m:n relations, index key is created separately for bar1 and bar2, and unique key is created for both columns bar1 and bar2.

In most cases, this query will be executed:

SELECT * FROM foos WHERE bar1=? AND bar2=?

The question is: Will query optimizer get benefit if index key created for both columns bar1 and bar2? That is:

ALTER TABLE foos ADD INDEX `idx_bar1_bar2` (`bar`,`bar2`)
1
  • 1
    You already have it: UNIQUE KEY uqx_bar1_bar2 (bar1,bar2). Even KEY idx_bar1 (bar1) is unnecessary.
    – mustaccio
    Commented Mar 12, 2018 at 16:48

2 Answers 2

4

More discussion on building indexes: http://mysql.rjweb.org/doc.php/index_cookbook_mysql

Furthermore your table smells like a many:many mapping table?? Here are several tips on efficiency for such: http://mysql.rjweb.org/doc.php/index_cookbook_mysql#many_to_many_mapping_table

0

There is already using primary key i.e, clustered Index and then used UNIQUE KEY on uqx_bar1_bar2 (bar1,bar2). So there is no more needed KEY idx_bar1 (bar1), KEY idx_bar2 (bar2).

1
  • Not quite right -- (bar1, bar2) does not help if you need (bar2); only leftmost works.
    – Rick James
    Commented Apr 2, 2018 at 13:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.