V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
peizhao2017
V2EX  ›  问与答

新手请教 MySQL 的 where in 语句的优化

  •  
  •   peizhao2017 · 2018-05-28 16:06:48 +08:00 · 3210 次点击
    这是一个创建于 2161 天前的主题,其中的信息可能已经有所发展或是发生改变。
    新手请教 MySQL 的 where in 语句的优化

    select id from 表 A where id in (select id from 表 B where id=$id) ORDER BY time DESC limit 0,50

    虽然能用
    但是很慢
    请教下还可以怎么写才能快些
    13 条回复    2018-05-29 14:14:51 +08:00
    Aluhao
        1
    Aluhao  
       2018-05-28 16:16:06 +08:00
    我也有类似这样写,不会慢哦;
    id in 里数据多吗?
    time 要索引,否则会很慢;
    peizhao2017
        2
    peizhao2017  
    OP
       2018-05-28 16:25:28 +08:00
    @Aluhao #1
    谢谢
    把 time 加上了索引
    有改善了
    但数据量稍微一多还是卡
    表 B 现在 30w 条数据
    id in 里面 5000 多条
    50 条一分页
    前几页速度还好
    到了后面很慢
    不知道哪里写的不对
    hahastudio
        3
    hahastudio  
       2018-05-28 16:26:00 +08:00
    试试 exists 或者 join
    peizhao2017
        4
    peizhao2017  
    OP
       2018-05-28 16:35:40 +08:00
    @hahastudio #3

    查了下
    有说法
    外层查询表小于子查询表,则用 exists,外层查询表大于子查询表,则用 in,如果外层和子查询表差不多,则爱用哪个用哪个
    我两个表差不多大
    换 exists 应该速度差不多

    join 一直没看懂
    我这条 sql 用 join 要怎么写呢
    ilylx2008
        5
    ilylx2008  
       2018-05-28 16:45:46 +08:00 via Android
    select id where id=$id 这没必要吧,估计你写错了。

    你把 in 语句和 select id 语句分开执行试试看。
    in 5000 个 id 一般不会慢
    peizhao2017
        6
    peizhao2017  
    OP
       2018-05-28 17:01:04 +08:00
    @ilylx2008 #5
    $id 是个程序传来变量值没写错

    又优化了下

    把 id 的 int 长度从 50 位改到 11 位
    都做了索引
    50 条一分页的情况下
    第一页飞快
    越往后翻页越慢

    阿里云的 1 核 1G 内存主机
    mysql 5.5
    php 7.2
    不知道哪里问题
    机器配置太差?
    turan12
        7
    turan12  
       2018-05-28 17:12:52 +08:00
    limit 就是越往后越慢
    polymerdg
        8
    polymerdg  
       2018-05-28 17:16:21 +08:00
    inner join 为什么不用
    peizhao2017
        9
    peizhao2017  
    OP
       2018-05-28 17:46:06 +08:00
    @polymerdg #8

    新手不会写
    要是用 inner join 要怎么写呢
    可以给个参考吗
    boks
        10
    boks  
       2018-05-29 13:46:00 +08:00
    select A.id from A,B where A.id = B.id and B.id=$id ORDER BY A.time DESC limit 0,50
    boks
        11
    boks  
       2018-05-29 13:47:04 +08:00
    你这 time 是创建时间吗? 如果是越后面越大的话可以用 id 代替
    peizhao2017
        12
    peizhao2017  
    OP
       2018-05-29 13:58:16 +08:00
    @boks #11

    time 是修改时间

    用 id 的话还是要再取修改时间再排序吧
    我直接按照修改时间倒序
    不知哪种排序法速度快些

    另外
    select A.id from A,B where A.id = B.id and B.id=$id ORDER BY A.time DESC limit 0,50
    没看懂
    有关键词吗我去学习下
    ccgoing10
        13
    ccgoing10  
       2018-05-29 14:14:51 +08:00
    A.IDB.ID 唯一就直接表关联,不唯一就 exists
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3005 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 08:25 · PVG 16:25 · LAX 01:25 · JFK 04:25
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.