Skip to content

Instantly share code, notes, and snippets.

@chroming
Created March 3, 2021 02:44
Show Gist options
  • Save chroming/97e0f579c607179aa14fd382efa90909 to your computer and use it in GitHub Desktop.
Save chroming/97e0f579c607179aa14fd382efa90909 to your computer and use it in GitHub Desktop.
MySQL字段值过大导致查询速度慢问题解决

MySQL在字段值过大(比如TEXT及能存更大内容的类型)时,即使查询时用到索引,速度也会很慢。如果暂时不方便改表结构,可以在不需要大字段值的时候不查询此字段,这样查询速度就正常了。

比如SQLalchemy中可以这么查:

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64))
    desc = db.Column(db.TEXT)
    
    list_columns = ['id', 'name']

    @classmethod
    def list_query(cls):
        """
        只查询list_columns定义的字段
        """
        return db.session.query(*(getattr(cls, c) for c in cls.list_columns))
        
     @property
     def nickname(self):
         return name

使用:

优化前: User.query.filter()

优化后: User.list_query().filter()

注意优化后返回的不是实例列表,故无法直接使用实例的@property(比如user.nickname)。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment