duanfang2708 2012-12-06 15:38
浏览 60
已采纳

MySQL基准测试:1个查询返回1000行VS 1000个单行查询[关闭]

Working on an app that requires a very large amount of data transferred from the DB. It includes SELECT and UPDATE queries both (i.e. read and write to the DB).

First I need to get a list of all the products (approx. 1000 SKUs). The SELECT query is very simple:

SELECT
    *
FROM
    `my_db`.`products`

Then some automatic updates are done to each product. The UPDATE query is something like this:

UPDATE
    `my_db`.`products`
SET
    `updated` = NOW(),
    `mods` = `mods` + 1,
    /* a couple more updated fields here, if needed */

Now the question is which one would be faster/better to perform: a single query that manipulates with all the records at once, or a PHP loop (e.g. foreach or while) that works with each product separately (1000 single-row queries)? The latter would require a WHERE model = 'ABC' and LIMIT 1, of course.

To make the matter more complex (and comprehensive), think of other affecting criteria, e.g.:

  • What if a different number of rows was targeted: 100 or 100,000?
  • What if more than one table was involved? See an example of a JOINed query below.

.

SELECT
    *
FROM
    `my_db`.`table1` AS `t1`
    INNER JOIN `my_db`.`table2` AS `t2` ON `t1`.`id` = `t2`.`fk`
    INNER JOIN `my_db`.`table3` AS `t3` ON `t2`.`id` = `t3`.`fk`
    /* Etc. */

Is there a general "rule of thumb" to decide which way is better in this or that situation?

  • 写回答

1条回答 默认 最新

  • douluohan3403 2012-12-06 15:55
    关注

    One good statement which includes 1000 records will always be more efficient than perform 1000 queries, as long as your sql statement is well written.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败