使用正则表达式和子选择的查询太慢

时间:2018-02-01 23:29:39

标签: mysql

我的PHP代码中有这个查询命中MySQL 5.5数据库。此查询的目的是生成下一个发票号,因此我需要确保获取最大现有发票号并向其添加1。

诀窍是此引用(invoice#)列是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秒,直到它被缓存。有没有什么方法可以加快速度,或者它是否能达到最佳状态?

1 个答案:

答案 0 :(得分:0)

请尝试这个,删除条款开销:

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]+$';
相关问题