PHP/mysql - 查询与数组?
我正在编写一个相当简单的 Web 应用程序,它从 mysql 数据库中的 3 个表中提取数据。因为我不需要大量的高级过滤,所以从理论上讲,构建然后在大型多维数组中工作似乎比尽可能执行 mysql 查询更快。
理论上,我可以只从每个表中进行一个查询,并使用结果构建大型数组,基本上不需要再次查询该表。这是一个好的做法,还是在需要时查询数据更好?或者是否存在某种平衡?如果有,那是什么?
I am writing a fairly simple webapp that pulls data from 3 tables in a mysql database. Because I don't need a ton of advanced filtering it seems theoretically faster to construct and then work within large multi-dimensional arrays instead of doing a mysql query whenever possible.
In theory I could just have one query from each table and build large arrays with the results, essentially never needing to query that table again. Is this a good practice, or is it better to just query for the data when it's needed? Or is there some kind of balance, and if so, what is it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
PHP 数组可以非常快,但这取决于这些表有多大,当数字变得很大时,MySQL 会更快,因为有了正确的索引,它就不必扫描所有数据,而只需选择那些你需要的。
我不建议你尝试你所建议的,MySQL有查询缓存,所以重复的查询甚至不会到达磁盘,所以在某种程度上,你正在考虑的优化已经完成了。
最后,正如克里斯所说,在不需要的时候永远不要考虑优化。
关于好的实践,好的实践是编写完成这项工作的最简单(且易于阅读)的代码。
如果最终您决定应用优化、分析性能,您可能会对意想不到的结果感到惊讶。
PHP arrays can be very fast, but it depends on how big are those tables, when the numbers get huge MySQL is going to be faster because, with the right indexes, it won't have to scan all the data, but just pick the ones you need.
I don't recommend you to try what you're suggesting, MySQL has a query cache, so repeated queries won't even hit the disk, so in a way, the optimization you're thinking about is already done.
Finally, as Chris said, never think about optimizations when they are not needed.
About good practices, a good practice is writing the simplest (and easy to read) code that does the job.
If in the end you'll decide to apply an optimization, profile the performance, you might be surprised, by unexpected results.
这取决于...
使用 microtime 函数尝试每个解决方案,您就会看到结果。
我认为 MySQL 查询缓存可能是一个很好的解决方案。如果您已过滤,则可以创建视图。
it depends ...
Try each solution with microtime function and you'll seethe results.
I think a MySQL Query cache can be a good solution. and if you've filtering on , you can create view.
如果您可以通过单个查询来完成它 - 那就去做吧!就你而言,我认为这是一个很好的做法。您还可以考虑将数据保存在 CSV 或类似文件中,这将为您提供更好的性能。
If you can pull it off with a single query - go for it! In your case, I'd say that is a good practice. You might also consider having your data in a CSV or similar file, which would give you even better performance.
我完全同意 chris 关于优化的观点:LAMP 堆栈对于 99% 的 Web 应用程序来说是一个很好的解决方案,无需任何优化。仅当您确实遇到性能问题时才进行优化。
对你的 php + 数据库的思维模型还有一个思考:你没有考虑到从数据库读取大量数据到 php 中也需要时间。
I absolutely concur with chris on optimizations: the LAMP stack is a good solution for 99% of web apps, without any need for optimization. ONLY optimize if you really run into a performance problem.
One more thought for your mental model of php + databases: you did not take into account that reading a lot of data from the database into php also takes time.