如何使用布尔条件搜索大数据 - Mysql

How to search a large data with a boolean condition - Mysql

我有一个很大的 table,有 3000 万行(每天都在增加)。 table 包括一些字段,例如 idstationIdsentAt(dateTime)、isApproved(tinyInt)、... I indexed column (stationId, sentAt).

这是我的查询:

Select  id, stationId, sentAt, isApproved
    from  monitoring_data_info
    where  stationId = 'akhdsjha12'
      and  isApproved = 1
    order by  sentAt DESC
    limit  1

数据库在 return 结果上浪费了很多时间,因为它必须搜索整个数据集才能与条件 isApproved = 1 进行比较。所以我的问题是:

您要添加此索引:

ALTER TABLE monitoring_data_info
 ADD INDEX (stationId, isApproved, sentAt);

索引中列的顺序很重要:

  • 前两列会将搜索减少到仅匹配的行。

  • 第三列将确保按您希望的顺序读取行 return,因此 ORDER BY 将是空操作。

您可能会喜欢我的介绍How to Design Indexes, Really, or the video of me presenting it。我解释了如何使用这样的索引优化查询。