简体   繁体   English

MySQL查询缓存中昂贵的查询?

[英]MySQL query cache for expensive queries?

I have this query which returns the top 10 selling products, and is used on the homepage: 我有此查询,该查询返回销售量最高的10种产品,并在首页上使用:

SELECT a.id, a.title, SUM(b.sold) as 'sold' FROM products a
LEFT JOIN stock b ON b.product_id = a.id
GROUP BY a.id ORDER BY sold DESC LIMIT 10

This information doesn't need to be current - it only needs to update maybe once a day. 该信息不需要是最新的-可能只需要每天更新一次。 So I had two questions, really: 因此,我确实有两个问题:

1) Considering this is evaluating the sold SUM of every single product (from a stock table where each product has multiple rows), is this a computationally expensive query - or rather would it be if this was a large database? 1)考虑到这是在评估每个单一产品的销售总和(从每个产品都有多行的库存表中),这在计算上是昂贵的查询吗?或者如果这是一个大型数据库, 那会是吗?

2) Could MySQL cache this query and only update it once per day? 2)MySQL可以缓存该查询并且每天仅更新一次吗? I am aware it has a query cache which it uses by default, but according to that this query would be invalidated every time the number of sold items changes. 我知道它有一个查询缓存,默认情况下会使用它,但是据此,每次售出物品数量发生变化时,该查询都会失效。

Am just looking for ways to be more efficient, to be honest. 老实说,我只是在寻找提高效率的方法。

What I'd do is cache it in the code that queries the database. 我要做的是将其缓存在查询数据库的代码中。 Keep a timestamp of the last time you queried, and if the timestamp is recent enough, return the cached result instead of running the query. 保留上一次查询的时间戳记,如果该时间戳记是最近的,则返回缓存的结果,而不是运行查询。 You could also use a caching system like memcached or Redis... and once you've got that set up, you'll probably find a hundred other places you can use it! 您还可以使用诸如memcached或Redis之类的缓存系统...完成设置后,您可能会发现一百多个可以使用它的地方!

Or, if there's no other content on your homepage that's dynamic, you could convert your homepage to a static HTML file that you generate once a day. 或者,如果主页上没有其他动态内容,则可以将主页转换为每天生成一次的静态HTML文件。 Simple & fast. 简单快捷。

1) It is as expensive as there are rows in the stock table. 1)它和库存表中的行一样昂贵。

2) No, mysql doesn't have anything like that. 2)不,mysql没有这样的东西。 To cache a single query, you should use application cache. 要缓存单个查询,应使用应用程序缓存。 It is fairly common requirement, and how you do it depends on your application and its architecture, of course. 这是相当普遍的要求,当然,如何实现取决于您的应用程序及其体系结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM