我有一个数据库,但我想到了速度问题。 因为我的所有数据都是单独保存的
Product table:
id int auto_inc PRI
name var_char(64)
attribute_table:
attr_id int auto_inc PRI
name var_char(64)
attribute_value:
attr_id int
product_id
value
但是当我进行高级搜索时,我会得到像
这样的大量查询select * from product_table as pt
cross join attribute_value as av ON av.product_id = pt.id AND av.value LIKE "test"
cross join attribute_table as at ON at.attr_id = av.attr_id AND at.name = "test"
cross join attribute_value as av ON av.product_id = pt.id AND av.value LIKE "test2"
cross join attribute_table as at ON at.attr_id = av.attr_id AND at.name = "test2"
cross join attribute_value as av ON av.product_id = pt.id AND av.value LIKE "test3"
cross join attribute_table as at ON at.attr_id = av.attr_id AND at.name = "test3"
但我想这不是很快。但有没有办法优化?或者我可以用一些技巧来更快地搜索,就像一种兑现?
答案 0 :(得分:0)
我相信你想要更像这样的东西:
select * from product_table as pt JOIN attribute_value as av
ON av.product_id = pt.id
WHERE (av.value LIKE "test")
OR (at.name = "test")
OR (av.value LIKE "test2")
OR (at.name = "test2") ....
通过从结果中选择,可以获得单个连接。我认为这更接近你想要的。
答案 1 :(得分:0)
首先,我会重写它(我不明白为什么你多次加入相同的表):
select * from product_table as pt
INNER join attribute_value as av ON (av.product_id = pt.id AND av.value LIKE "test%")
INNER join attribute_table as at ON (at.attr_id = av.attr_id AND at.name LIKE "test%")
接下来,运行EXPLAIN SELECT ...
以检查执行是否正常。它显示了当前用于查询的索引
然后,确保在用于连接表的列上有索引 - 您应该在attribute_value.product_id,attribute_table.attr_id上有索引(至少)。
最后,只选择您需要的内容,而不是*
。