我有以下表格:
包含以下字段:
产品:
分类
子分类
品牌
我想要的是进行查询,用户输入一个或多个单词,然后搜索我上面的所有字段。
这是我现在的查询:
SELECT DISTINCT p. *
FROM products p, categories c, subcategories s, brands m
WHERE p.name LIKE 'word%'
OR p.description1 LIKE 'word%'
OR p.description2 LIKE 'word%'
OR p.description3 LIKE 'word%'
OR (
c.name LIKE 'word%'
AND c.id = p.id_category
)
OR (
s.name LIKE 'word%'
AND s.id = p.id_subcategory
)
OR (
m.name LIKE 'word%'
AND m.id = p.id_brand
)
LIMIT 10 ;
有没有办法调整此查询以使其更快?数据库已经有很多产品,所以我怀疑这个查询显示的时间可能是因为......
任何sugestions?
谢谢!
答案 0 :(得分:1)
这样的事情可以解决问题:
SELECT DISTINCT p. *
FROM products p
LEFT JOIN categories c ON c.id = p.id_category
LEFT JOIN subcategories s ON s.id = p.id_subcategory
LEFT JOIN brands m ON m.id = p.id_brand
WHERE p.name LIKE 'word%'
OR p.description1 LIKE 'word%'
OR p.description2 LIKE 'word%'
OR p.description3 LIKE 'word%'
OR ( IFNULL(c.name, '') LIKE 'word%' )
OR ( IFNULL(s.name, '') LIKE 'word%' )
OR ( IFNULL(m.name, '') LIKE 'word%' )
LIMIT 10;
答案 1 :(得分:1)
如果全文搜索不是一个选项,并假设您已对表进行了适当索引,则可以尝试限制已连接表的结果集。
SELECT DISTINCT p.*
FROM products p
LEFT OUTER JOIN (
SELECT DISTINCT id
FROM categories
WHERE name LIKE 'word%'
LIMIT 10
) c ON c.id = p.id_category
LEFT OUTER JOIN (
SELECT DISTINCT id
FROM subcategories
WHERE name LIKE 'word%'
LIMIT 10
) s ON s.id = p.id_subcategory
LEFT OUTER JOIN (
SELECT DISTINCT id
FROM brands
WHERE name LIKE 'word%'
LIMIT 10
) m ON m.id = p.id_brand
WHERE p.name LIKE 'word%'
OR p.description1 LIKE 'word%'
OR p.description2 LIKE 'word%'
OR p.description3 LIKE 'word%'
LIMIT 10
答案 2 :(得分:0)
首先,我将WHERE子句中的条件连接替换为JOIN
FROM products p INNER JOIN categories c ON c.id = p.id_category INNER JOIN subcategories s ON s.id = p.id_subcategory INNER JOIN brands m ON m.id = p.id_brand
(如果你有可用的FK,则使用LEFT JOIN)
然后您需要在产品(名称),产品(描述1),产品(描述2),(描述3),类别(名称),子类别(名称)和品牌(名称)上有索引