我一直在努力创建正确的索引来提高我们在数据库上运行的特定查询的性能,我希望你们中的一位可以帮助我指出正确的方向。
我有两张桌子,如下所示。我有一个查询,以查找属于特定类别的公司的所有员工,例如first_name,例如“Be%”。我尝试在category_id, company_id
上创建一个多索引,但这没有帮助。索引表的正确方法应该是什么,以便为此查询获得更好的性能?提前谢谢。
SELECT
e.*
FROM employee e
INNER JOIN company c ON e.company_id = c.company_id
WHERE c.category_id = 6
AND e.first_name LIKE "Be%"
GROUP BY e.employee_id
TABLE公司
| company_id | category_id |
+------------+-------------+
| ... | ... |
+------------+-------------+
| 47 | 6 |
+------------+-------------+
| .. | ... |
+------------+-------------+
| 252 | 6 |
+------------+-------------+
TABLE员工
| employee_id | company_id | first_name | ... |
+-------------+------------+------------+-----+
| 2582250 | 47 | Ben | ... |
+-------------+------------+------------+-----+
| 3447890 | 252 | Ryan | ... |
+-------------+------------+------------+-----+
| 7125966 | 252 | Beth | ... |
+-------------+------------+------------+-----+
| ... | ... | ... | ... |
+-------------+------------+------------+-----+
创建下面的表格和sqlfiddle。
CREATE TABLE company (
`company_id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`category_id` INT UNSIGNED NOT NULL DEFAULT 0
) ENGINE=InnoDB;
CREATE TABLE employee (
`employee_id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`company_id` INT UNSIGNED NOT NULL,
`first_name` VARCHAR(255)
) ENGINE=InnoDB;
答案 0 :(得分:1)
你必须拥有多个索引:很多表。遵循here概述的建议。
WHERE c.category_id = 6
AND e.first_name LIKE "Be%"
需要
c: INDEX(category_id, company_id) -- which will be called for in the link above
e: INDEX(first_name, employee_id)
优化工具将以c
开头,然后进入e
。或相反亦然。我正在为你提供最佳指标。