duangan6133 2011-07-17 05:49
浏览 27
已采纳

mysql多行选择性能

is there any performance difference between:

SELECT * FROM table WHERE id IN (1,2,3)

versus

SELECT * FROM table WHERE id = 1
SELECT * FROM table WHERE id = 2
SELECT * FROM table WHERE id = 3

whereby you execute each query, so there are 3 total queries to be executed by PHP

  • 写回答

5条回答 默认 最新

  • donglong7338 2011-07-17 06:39
    关注

    Both of the examples provided do different things although they may look similar. Use the construct designed to do what you want. Worrying about "optimization" here is silly and premature: a good model and good design should come first.

    The first case is one query -- it returns one result set (of presumably up to 3 items, assuming that ID is a PK). The order of records in the set is not defined as there is no ORDER BY.

    The second case has three queries -- and thus three result sets (the order of the result sets in relationship to each-other is defined) -- each result set (assuming again that ID is a PK) will result in 0 or 1 records.

    Now, if only it were that simple... depending on whether the second was executed inside a transaction or not (and what isolation level of transaction and what guarantees the backend makes) determines if the same items are guaranteed to be returned in both cases. That is, imagine the record with ID=2 is deleted after the SELECT ID=1 but before SELECT ID=2 -- what should the results be?

    All that being said, the "correct" choice is likely the single select, although it is possible to imagine pathological cases where the second is desired. As a bonus, it is also generally easier to deal with a single result set.

    I suspect the first case will also be [slightly] better performing just because of the small overheads for query execution and, in any case, it should be no slower than the second. The difference in performance may or may not be negligible depending upon other factors including connection latency. However, the only way to know "for certain" is to run performance tests on actual data/usage and inspect query plans (see EXPLAIN).

    Happy coding.

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

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)