MySQL 中 EXISTS 与 IN 的子查询:性能比较
子查询在从数据库中提取特定数据方面发挥着至关重要的作用。两种常见的子查询方法是 EXISTS 和 IN。虽然两者都可以实现相似的结果,但它们表现出不同的性能特征。
考虑以下两个查询:
方法 1:
SELECT * FROM tracker WHERE reservation_id IN ( SELECT reservation_id FROM tracker GROUP BY reservation_id HAVING ( method = 1 AND type = 0 AND Count(*) > 1 ) OR ( method = 1 AND type = 1 AND Count(*) > 1 ) OR ( method = 2 AND type = 2 AND Count(*) > 0 ) OR ( method = 3 AND type = 0 AND Count(*) > 0 ) OR ( method = 3 AND type = 1 AND Count(*) > 1 ) OR ( method = 3 AND type = 3 AND Count(*) > 0 ) );
方法2:
SELECT * FROM tracker t WHERE EXISTS ( SELECT reservation_id FROM tracker t3 WHERE t3.reservation_id = t.reservation_id GROUP BY reservation_id HAVING ( METHOD = 1 AND TYPE = 0 AND COUNT(*) > 1 ) OR ( METHOD = 1 AND TYPE = 1 AND COUNT(*) > 1 ) OR ( METHOD = 2 AND TYPE = 2 AND COUNT(*) > 0 ) OR ( METHOD = 3 AND TYPE = 0 AND COUNT(*) > 0 ) OR ( METHOD = 3 AND TYPE = 1 AND COUNT(*) > 1 ) OR ( METHOD = 3 AND TYPE = 3 AND COUNT(*) > 0 ) );
从性能角度来看,方法 2 明显优于方法 1,执行时间不到 1 秒,而执行时间超过 10 秒。要理解这种差异的原因,我们必须深入研究每种方法的内部工作原理。
EXISTS 与 IN:主要差异
性能注意事项
结论
一般来说,EXISTS是当子查询预计返回大量行或涉及空值时建议使用。对于小型子查询,IN 可以提高性能。始终建议使用解释计划来确定特定查询的最佳方法。
以上是MySQL 子查询中的 EXISTS 与 IN:哪个性能更好?的详细内容。更多信息请关注PHP中文网其他相关文章!