我的问题是:
select * from
(
select * from barcodesA
UNION ALL
select * from barcodesB
)
as barcodesTOTAL, boxes
where barcodesTotal.code=boxes.code;
表格barcodesA有4000个条目 表 barcodesB 有 4000 个条目 表格框有大约 180.000 个条目
处理查询需要 30 秒。
另一个有问题的查询:
select * from
viewBarcodesTotal, boxes
where barcodesTotal.code=boxes.code;
viewBarcodesTotal 包含来自两个条形码表的 UNION ALL。它也需要永远。
同时,
select * from barcodesA , boxes where barcodesA.code=boxes.code
UNION ALL
select * from barcodesB , boxes where barcodesB.code=boxes.code
这个需要 <1 秒。
问题显然是为什么?我的代码有问题吗? mysql 有问题吗?
我必须从访问权限迁移到 mysql,如果第一个选项出现问题,我将不得不重写我的所有代码。
最佳答案
如果您还没有索引,请在 boxes.code
上添加索引。将 8000 条记录 (4K+4K) 加入 180,000 条记录将受益于等式 180K 一侧的索引。
此外,在您的 SELECT 语句中明确指定您需要的字段。在生产用途查询中使用 * 是一种糟糕的形式,因为它鼓励您不必考虑哪些字段(以及它们可能有多大),更不用说您的示例中有 2 个不同的表,barcodesa
和 barcodesb
可能具有不同的数据类型和您正在联合的列顺序....
关于JOIN性能不佳的mysql子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9049146/