V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
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 · Sep 30, 2017 · 5334 views
    This topic created in 3141 days ago, the information mentioned may be changed or developed.

    用 sqlalchemy 在 mysql 里查用户数据:

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

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

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

    是的,userid 是唯一的。
    Finest
        6
    Finest  
       Sep 30, 2017
    既然唯一,后面的注册时间条件程序判断都可以了
    tb4649120073rs
        7
    tb4649120073rs  
       Sep 30, 2017
    @miniyao
    如果 userid 是唯一的,而 where 条件里面有 User.id=userid
    已经可以直接根据 userid 拿出一行记录,一般够用了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   985 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 19:09 · PVG 03:09 · LAX 12:09 · JFK 15:09
    ♥ Do have faith in what you're doing.