Mysql 哪个查询的性能更好?
我有以下三个表格:Mysql 哪个查询的性能更好?,mysql,query-performance,mysql-5.7,Mysql,Query Performance,Mysql 5.7,我有以下三个表格: 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
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)
查询必须使用参数集检查条目中是否存在记录
假设参数设置如下:
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
- 作为角色的主体id:2
- 对象ID:45
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个用户在任何时候都在系统上同时工作
PS:我读过关于比较子查询和联接的内容,但我的问题并不是简单的比较(SELECT…)
中的比较通常效率很低
或
通常效率低下
连接通常比其他表达方式更有效
这个
这样可能会更快:
where pid IN (2,3)
AND ((pid=2 AND role)
OR (pid=3 AND !role)
)
如果可以有效地使用索引来限制在撒尿2和3之前撒尿的努力,那么速度可能会加快
尝试其他人的评论和我的建议,并提供CREATE
TABLE和EXPLAIN
。然后我可以建议索引。当然看起来像一个简单的比较。。为什么不生成一堆测试数据并对查询计时?@Oli我已经生成了数据,并使用我的笔记本电脑和xampp进行了测试。当我在phpMyAdmin中多次运行查询时,执行时间每次都会减少,并以毫秒的速度停止。所以我不知道我是否应该相信这个结果…看看这个@Oli谢谢你的链接。即使使用SQL\u NO\u缓存
似乎也不能阻止mysql使用操作系统或池缓存。所以我每次都需要重启mysql服务器。我之所以说这不是一个比较,是因为查询可以结合两种方法甚至其他方法编写,不幸的是,我不知道如何使用explain
关键字的结果来优化查询。嗯,我认为始终使用JOIN语句是最佳做法。与其他可能的瓶颈(如不正确的索引、表结构等)相比,速度差异可以忽略不计。如果您真的对优化查询感兴趣,请阅读解释函数的一些文档。昨天,我分析了架构结构,发现我可以简单地创建另一个表,与具有不同名称的entry
相同,我可以删除principal
和class
,因此不再需要联接或子查询。感谢您的帮助,提示检查pid
和角色
非常重要。