我在MySQL 5.1上具有以下架构
CREATE TABLE `mytest` (
`category` varchar(32) ,
`item_name` varchar(255)
KEY `key1` (`category`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
类别列充满像这样
[:parent_parent_cat_id][:parent_cat_id][:leaf_cat_id]
10000200003000
如果您可以搜索以下所有类别:parent_parent_category_id
SELECT * FROM mytest WHERE category LIKE "10000%";
它使用索引key1;
但
我想搜索:parent_cat_id时如何使用索引?
SELECT * FROM mytest WHERE category LIKE "%20000%";
您有更好的解决方案吗?
解决方法:
该模型称为物化路径.
您只需要在单独的表中进行分类,并使项目引用该表即可,而不是路径:
SELECT i.*
FROM categories c
JOIN items i
ON i.category = c.id
WHERE c.path BETWEEN
(
SELECT path
FROM categories ci
WHERE ci.id = '20000'
)
AND
CONCAT(
(
SELECT path
FROM categories ci
WHERE ci.id = '20000'
), ':')