V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
MySQL 5.5 Community Server
MySQL 5.6 Community Server
Percona Configuration Wizard
XtraBackup 搭建主从复制
Great Sites on MySQL
Percona
MySQL Performance Blog
Severalnines
推荐管理工具
Sequel Pro
phpMyAdmin
推荐书目
MySQL Cookbook
MySQL 相关项目
MariaDB
Drizzle
参考文档
http://mysql-python.sourceforge.net/MySQLdb.html
miniyao
V2EX  ›  MySQL

MySQL 查询一条语句里有一个索引就够了吗?比如 q = User.query.filter(User.id==userid, User.register_time > last_year).all() 只加一个 id 的索引可行?

  •  
  •   miniyao · 2017-09-30 12:52:00 +08:00 · 4344 次点击
    这是一个创建于 2393 天前的主题,其中的信息可能已经有所发展或是发生改变。

    用 sqlalchemy 在 mysql 里查用户数据:

    q = User.query.filter(User.id=userid, User.register_time > last_year).all()
    

    只给 User 表的 id 加索引就够了吗?有没有必要给 User 表的 register_time 也增加索引呢?加两个索引时间检索速度有提升吗?

    7 条回复    2017-09-30 21:10:41 +08:00
    teddy2725
        1
    teddy2725  
       2017-09-30 13:08:44 +08:00   ❤️ 1
    加一个联合索引
    nullcoder
        2
    nullcoder  
       2017-09-30 16:24:04 +08:00   ❤️ 1
    设计到表设计的问题,要结合具体的业务场景来定。
    加索引检索速度提升,但存储成本增加
    petelin
        3
    petelin  
       2017-09-30 17:32:49 +08:00   ❤️ 1
    可行, userid 应该是唯一的吧? 数据库会直接捞出那条记录, 然后比对一下 时间.
    GTim
        4
    GTim  
       2017-09-30 18:02:50 +08:00   ❤️ 1
    可行,看这字段
    miniyao
        5
    miniyao  
    OP
       2017-09-30 18:19:17 +08:00 via Android
    @petelin
    @GTim

    是的,userid 是唯一的。
    hand515
        6
    hand515  
       2017-09-30 19:08:34 +08:00
    既然唯一,后面的注册时间条件程序判断都可以了
    tb4649120073rs
        7
    tb4649120073rs  
       2017-09-30 21:10:41 +08:00
    @miniyao
    如果 userid 是唯一的,而 where 条件里面有 User.id=userid
    已经可以直接根据 userid 拿出一行记录,一般够用了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1203 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 23:53 · PVG 07:53 · LAX 16:53 · JFK 19:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.