我因索引问题而陷入困境......我有两张桌子:
产品:
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
+----+
products_relations
+------------+-----------------+----------+
| product_id | product_link_id | priority |
+------------+-----------------+----------+
| 4084 | 3554 | 1 |
| 8515 | 6680 | 1 |
| 4084 | 1248 | 2 |
+------------+-----------------+----------+
当我运行此查询时
SELECT
`products`.*,
products_relations.product_link_id
FROM
`products`
LEFT JOIN products_relations
ON products_relations.product_id = `products`.id
未使用索引:
+----+-------------+--------------------+------------+-------+---------------+---------+---------+------+------+----------+----------------------------------------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+--------------------+------------+-------+---------------+---------+---------+------+------+----------+----------------------------------------------------+
| 1 | SIMPLE | products | NULL | index | NULL | PRIMARY | 4 | NULL | 5790 | 100.00 | Using index |
| 1 | SIMPLE | products_relations | NULL | ALL | product_id | NULL | NULL | NULL | 4 | 100.00 | Using where; Using join buffer (Block Nested Loop) |
+----+-------------+--------------------+------------+-------+---------------+---------+---------+------+------+----------+----------------------------------------------------+
为什么?
这是我的架构,如果你想尝试一下。
为了使其更具可读性,我对其进行了简化,但索引问题仍然存在。
CREATE TABLE `products_relations` (
`product_id` int(11) NOT NULL,
`product_link_id` int(11) NOT NULL,
`priority` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `products_relations`
ADD KEY `product_id` (`product_id`);
CREATE TABLE `products` (
`id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `products`
ADD PRIMARY KEY (`id`);
ALTER TABLE `products`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;