我有以下查询,它只从一个表中获取数据。
编辑: 这是一个应该为自动完成功能返回数据的查询。
- 自动完成数据可以在
text1
或中text2
。 - 确切的匹配应该在顶部。
int3
是一个整数权重值,其中结果的顺序以此为基础。前两个查询用于识别完全匹配。 - 接下来的两个查询用于识别近似匹配。
WHERE text1 > 'foo' AND text1 < 'fop'
短语实际上等于WHERE text1 LIKE 'foo%'
。我这样写是为了从索引中受益。
希望这可以帮助。
SELECT DISTINCT text1 as Key, 'text1' as Source, int1 as Count, 1000 as int3
FROM mytable
WHERE text1 = 'foo'
UNION SELECT DISTINCT text2 as Key, 'text2' as Source, int2 as Count, 1000 as int3
FROM mytable
WHERE text2 = 'foo'
UNION SELECT text1 as Key, 'text1' as Source, int1 as Count, MAX(int3) as int3
FROM mytable
WHERE text1 > 'foo' AND text1 < 'fop' AND Count < 4
GROUP BY Key
UNION SELECT text2 as Key, 'text2' as Source, int2 as Count, MAX(int3) as int3
FROM mytable
WHERE text2 > 'foo' AND text2 < 'fop' AND Count < 4
GROUP BY Key
ORDER BY int3 DESC, Count, Key LIMIT 0, 15;
表结构为:
CREATE TABLE mytable (text1 TEXT, text2 TEXT,
int1 NUMERIC, int2 NUMERIC, int3 NUMERIC);
它工作正常,但我需要微调性能。我尝试了不同的索引选项并使用内置计时器检查了性能结果。
我发现的最佳索引选项是:
CREATE INDEX cmp1 ON mytable (text1 ASC, int1 ASC, int3 DESC);
CREATE INDEX cmp2 ON mytable (text2 ASC, int2 ASC, int3 DESC);
如果您能向我展示任何更好的索引选项或性能更好的 SQL 查询,我会很高兴。