我的 PHP 代码中有这个查询命中了 MySQL 5.5 数据库。此查询的目的是生成下一个发票编号,因此我需要确保获得最大的现有发票编号并将其加 1。
诀窍是这个引用(发票编号)列是一个 varchar,因此用户可以输入字母数字字符,所以我的查询只需要查看数值。
select max(cast(t.reference as unsigned)) reference
from transactions t, families f
where t.familyid in (select id from families where companyid = 1415)
and t.familyid = f.id
and transactiontype = 'C'
and t.reference REGEXP '^[0-9]+$';
如您所见,我正在使用正则表达式,因为我想要做的是获取引用列中当前存在的最大数字,以便生成下一个发票编号。
当前查询需要 2 到 8 秒才能被缓存。有没有什么方法可以加快速度,或者它是否已经达到了最佳状态?
最佳答案
请试试这个,在子句开销中删除:
select max(cast(t.reference as unsigned)) reference
from transactions t, families f
where
t.familyid = f.id
and f.companyid = 1415
and t.transactiontype = 'C'
and t.reference REGEXP '^[0-9]+$';
关于mysql - 使用正则表达式和子选择查询太慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48573435/