2非常快速和简单的查询在合并在一起时非常慢

lh80um4z  于 2021-06-20  发布在  Mysql
关注(0)|答案(4)|浏览(360)

我有这两张table。我正在尝试查找id为1的用户加入的组。下面是每个表的10行(只是为了显示它们的布局):
posttable(57272行,主键id):

+----+---------+
| id | groupid |
+----+---------+
|  0 |       1 |
|  1 |       1 |
|  3 |       1 |
|  4 |       1 |
|  5 |       1 |
|  9 |       1 |
| 10 |       1 |
| 13 |       1 |
| 15 |       1 |
| 17 |       1 |
+----+---------+

joinedgroupstable(258404行,唯一索引userid,groupid):

+--------+---------+--------+
| id     | groupid | userid |
+--------+---------+--------+
| 258010 |       1 |      1 |
| 258484 |       6 |      1 |
|    172 |       1 |      2 |
|    173 |       2 |      2 |
|    174 |       3 |      2 |
|    175 |       4 |      2 |
|    176 |       5 |      2 |
|    177 |       6 |      2 |
|    178 |       8 |      2 |
|    179 |       9 |      2 |
+--------+---------+--------+

当我尝试运行此查询时,它几乎在3秒内完成,这非常慢:

SELECT * FROM posttable p 
WHERE groupid in (SELECT groupid FROM joinedgroupstable WHERE userid=1)
ORDER BY p.ID DESC LIMIt 25;

我也尝试过使用内部连接而不是where-in,但结果大致相同:

SELECT * FROM posttable p 
INNER JOIN joinedgroupstable jg ON userid=1 AND jg.groupid=p.groupid
ORDER BY p.ID DESC LIMIt 25;

下面是两个查询的解释选择(两个查询的结果相同):

|| *id* || *select_type* || *table* || *partitions* || *type* || *possible_keys* || *key* || *key_len* || *ref* || *rows* || *filtered* || *Extra* ||
|| 1 || SIMPLE || jg ||  || ref || UserID_GroupID,userid || UserID_GroupID || 4 || const || 2 || 100.00 || Using index; Using temporary; Using filesort ||
|| 1 || SIMPLE || p ||  || ref || groupid || groupid || 4 || thyra.jg.groupid || 60 || 100.00 ||  ||

问题是,单独运行每个查询非常快:

SELECT * FROM posttable p ORDER BY p.ID DESC LIMIt 25;

SELECT * FROM joinedgroupstable WHERE userid=1

考虑到每个查询本身运行得非常快,但合并时运行得很慢,会有什么错呢?

bfnvny8b

bfnvny8b1#

我会用 EXISTS 相反,这也可能表现得更好:

select p.*
from posttable p 
where exists (select 1 
              from joinedgroupstable jg
              where jg.groupid = p.groupid and jg.userid = 1
              )
order by p.id desc
limit 25;
qzwqbdag

qzwqbdag2#

如果你的问题简单化了 PostTable 包含的列比您显示的多,您的 ORDER BY ... LIMIT ... 子句导致了大量的排序浪费。
您可以执行所谓的“延迟连接”,首先获取适当的id值,然后使用它们来检索行。

select p.* 
  from posttable p
  join (
       select a.id
       from posttable a
       join joinedgroupstable g on a.groupid = g.groupid
      where g.userid = 1
      order by a.id desc
      limit 25
     ) sel on sel.id = p.id
order by p.id desc
limit 25;

这限制了昂贵的 ORDER BY ... LIMIT ... 手术只是为了 id 列,然后使用所选 id 值只命中主表25次。

fsi0uk1n

fsi0uk1n3#

不同的答案:

create index ix10 on joinedgroupstable (userid);

create index ix11 on posttable (groupid);

select p.* 
  from posttable p
  join joinedgroupstable g on p.groupid = g.groupid
  where g.userid = 1
  order by p.id desc
  limit 25;
erhoui1w

erhoui1w4#

要加快第一个查询的速度,请添加以下索引:

create index ix1 on joinedgroupstable (userid, groupid);

create index ix2 on PostTable (id);

第二个问题在我看来是错误的。

相关问题