MYSQL 索引计算的正确方法 where 条件 ( where myTable.a > myTable.b)

MYSQL proper way to index calulated where conditions ( where myTable.a > myTable.b)

MySQL --版本为 5.7.18

什么是优化查询的正确方法,例如:

select id,name from mytable where a - b > 0

其中 mytable 类似于

ab 列添加索引会有帮助吗?我应该只添加第三列 a_minus_b,为其编制索引,然后每次都小心地正确更新它,还是有更好的方法?

您可以使用生成的列,然后在该列上使用索引:

alter table mytable add column abdiff int generated always as (a - b);

create index idx_mytable_abdiff on mytable(abdiff);

注意:这使用 int 作为类型。您可以指定您喜欢的不同类型。