dpwtr666638 2017-09-17 04:18
浏览 198
已采纳

UNION与UNION ALL的表现

I am selecting a single column of foreign keys from multiple tables through either UNION or UNION ALL.

It is generally recommended to use UNION ALL instead of UNION for performance issues when duplicates do not matter. However, in my calling PHP script it would be more efficient to loop through and manipulate the data without duplicates.

So, I can use either of the following options:

Option 1:

Use UNION in the database to eliminate duplicates

Option 2:

use UNION ALL in the database and eliminate the data in my PHP script using array_unique() or other similar functions.

My assumption is that Option 1 would be the preferred and more efficient method in the majority of cases, however I have nothing to back up that assumption, and not sure the best way to test it especially since it would likely depend a lot on what the data was.

Is my assumption correct in most cases? If so, why? If not, why not?

  • 写回答

2条回答 默认 最新

  • dongpouda6700 2017-09-17 06:25
    关注

    The mainly aspect is that UNION is shortcut for UNION DISTINCT and so

    the difference in performance between UNION and UNION ALL are related to the
    need to obtain a distinct result and for this the database engine and the query optimizer are surely more effective and most efficient than the filtring alogoritm based on PHP code in application.

    The dictinct Operation can, moreover, benefit from the pre-optimizations for group by functionality

    Not only, the duplicate data filtering is generally based on ordered data while the select sql functions work without explicit ordering, and therefore the need for filtering data with the application can lead to less efficient and more longer queries.

    Generally the db engine is much more efficient that application PHP functions code so the Option 1 is generally the better choise

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。