在数据库中存储行数或动态获取
Say I have a table full of comments, each from different users, and I want to count how many comments each user has. Should I have a separate table with the count, and update that on creation/deletion of comments, or should I query the count every time?
假设我有一个满是评论的表,每个都来自不同的用户,我想计算每个用户有多少评论。我应该在创建/删除注释时使用一个单独的计数表,并对其进行更新,还是应该每次都查询计数?
I feel like the latter is better, but I want some more experienced input on the matter. Thanks.
我觉得后者更好一些,但我希望在这个问题上有更多的经验。谢谢。
3 个解决方案
#1
2
Following the good old YAGNI principle, I would suggest you go with the simplest solution for now, which is just counting the number of comments as needed. This is just pragmatic coding.
遵循古老的YAGNI原则,我建议您暂时使用最简单的解决方案,即根据需要计算注释的数量。这只是一种实用的编码。
If, down the line, you find this is causing even small performance problems, then you should replace it with a cached value using a stored procedure or similar, but chances are it will serve you just fine.
如果您最终发现这甚至会导致很小的性能问题,那么您应该使用存储过程或类似的方法将其替换为缓存值,但它很可能会很好地为您服务。
So, I realise this probably isn't the clear answer you want, but: if you're making something small, go with the easy solution (counting); if you're making something bigger, go with the easy solution (counting) then upgrade to the harder solution (storing a value) if you find you need it. If you know what you're making is guaranteed to be big (lucky you!) then fine, go straight for the harder solution.
所以,我意识到这可能不是你想要的明确答案,但是:如果你正在做一个小的事情,就用简单的解决方案(计数);如果你正在做一些更大的事情,选择简单的解决方案(计数),然后升级到更难的解决方案(存储一个值),如果你发现你需要它。如果你知道你正在做的东西一定会很大(幸运的是你!),那好吧,直接去找更难的解决方案。
Note: I've said "harder solution" but as you probably know it's only fractionally harder than the easy solution.
注意:我说过“更难的解决方案”,但是你可能知道,它只比简单的解决方案稍微难一点。
更多相关文章
- MySql 修改列的注释信息的方法
- mysql主从同步报slave_sql_running:no的解决方案
- 使用来自相同表注释的两个外键来休眠
- win7下Django的MySql安装,问题解决方案
- mysql 事物没提交导致事物一直运行解决方案
- 无法连接远程MySQL数据库的解决方案
- [征集] MySQL交叉表解决方案及散分
- PHP MYSQL 出现中文乱码的解决方案
- Amoeba for MySQL---分布式数据库Proxy解决方案