我有 3 个查询从大约 170,000 条记录的数据库中以限制 1 结尾。
如果我分别运行这 3 个查询或使用 UNION 组合所有 3 个查询是否会提高速度?目前查询返回结果很慢。
所以最终结果会从数据库中返回3条记录。
我当前的查询:
select * from table where cat = '%1%' and brand like '%example%' limit 1;
select * from table where cat = '%2%' and brand like '%example2%' limit 1;
select * from table where cat = '%3%' and brand like '%example3%' limit 1;
联合:
(select * from table where cat = '%1%' and brand like '%example%' limit 1) UNION (select * from table where cat = '%2%' and brand like '%example2%' limit 1) UNION (select * from table where cat = '%3%' and brand like '%example3%' limit 1);
最佳答案
union
将执行所有三个查询,然后尝试从中删除重复项,因此它几乎肯定会降低 性能。使用 union all
而不是运行三个单独的查询可能会略微提高性能,因为它将节省三个独立执行的来回。
关于MySQL 多查询限制为 1,UNION 会提高速度吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26570234/