哪个查询的性能更好?

问题描述 投票:0回答:1

我有3张桌子,如下所示:

class
  id:bigint(PK)
  name:varchar


principal:
  id: bigint(PK)
  pid:bigint
  flag:boolean
  uniqueConstraint(pid, flag)

entry:
  cid: (FK, reference class)
  pid: (FK, refernce principal)
  object_id: bigint
  code: tinyint
  PK: (cid, pid, obj)

查询必须使用参数集检查条目中是否存在记录。

假设参数集如下:

  • 班级名称:班级3
  • 作为用户的主要ID:3
  • 主要身份作为角色:2
  • 对象ID:45

我写了2个查询,一个使用join,一个使用sub-query

查询编号1:

select id from entry where pid in
    (select id from principal
         where (pid=2 AND role)
            OR (pid=3 AND !role)
    )
    AND cid = (select id from class where name='Class#3')
    AND object_id=45

和查询编号2:

select e.id from class c
            inner join entry e on e.cid=c.id and c.name='Class#3'
            inner join principal p on p.id=e.pid 
                     and p.id in ( select id from principal
                         where (pid=2 AND role)
                            OR (pid=3 AND !role)
                                 )
    where e.object_id=45

当然还有检查代码的附加条件,我没有在查询中包括它。

我想知道哪个在大规模生产环境中表现更好。假设类中有100行,主体有10000行,“ entry”中有超过250000行,并且必须为每个请求执行查询(如所说明的那样),并且至少有3000个用户在任何时间连续且同时在系统上工作。 >

  1. 这些查询中的哪一个查询会更好,为什么?原因是这样对于后续工作很重要
  2. 是否有比这两种方法更好的方法来编写查询甚至更好的方法来构建模式?
  3. 问候


PS:我已经阅读了有关比较子查询和联接的this question,但我的问题并非完全是简单的比较

我有3张表,如下所示:类id:bigint(PK)名称:varchar主体:id:bigint(PK)pid:bigint标志:boolean uniqueConstraint(pid,标志)条目:cid:(FK,参考类)pid :(FK,...

mysql query-performance mysql-5.7
1个回答
0
投票

IN ( SELECT ... )通常效率低下。

© www.soinside.com 2019 - 2024. All rights reserved.