dongyou2305 2017-04-18 02:12
浏览 17
已采纳

从SQL存储计数更有效吗? 有什么缺点(同步等)?

I have a MySQL database with two tables I am interested in querying:

Users: Stores information about users such as userID etc.

Map: A map table containing about 7 million mapIDs (an index referring to a physical lat/long on earth).

Many of these mapIDs are associated to userIDs, so for example user #1 may have 10 mapIDs associated with him, user #2 may have 100 etc.

I am interested in knowing what is more efficient/safer/best practice to count how many mapIDs belong to a user when I query the database with a userID:

1) Query the Map table to count how many mapIDs belong to the userID, OR

2) Store the number of mapIDs belonging to users in an additional column in the Users table (e.g. mapCount), and only query this value (rather than searching the large Maps table each time).

I know option 2 will be faster, but I am worried about potential problems with synchronization etc. For example, every time a user performs an action (e.g. add a mapID to his account) I would add the userID to the associated mapID on the Maps table, and also increment the mapCount value in Users so that subsequent searches/actions will be faster. But what if the second query failed for some reason and the mapCount field fell out of synch? Is this worth the risk?

What is generally the best thing to do in this situation?

  • 写回答

3条回答 默认 最新

  • dream752614590 2017-04-18 02:18
    关注

    If you are building the database, start by using a query to extract the data you want using a query. You can optimize this query by adding an index on map(usersId). If the performance is adequate, you are done.

    If performance is not sufficient, then you can consider storing the count separately. Maintaining the count requires triggers on insert and delete and possibly on update.

    These triggers will have an effect on performance when adding and modifying data. This is usually small, but it can be important. If you are doing bulk-load operations, then you will need to manually handle the summarization values.

    All this maintenance is a lot of work, and you should only go down that path if you really need to do it that way.

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

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?