如何解决由于 subselect
我有以下sequilize代码:
return await Db.events.findOne({
where: {eventId,deleted: "0",blocked: "0","approved": "1" },include: [
{
model: Db.users,required: false,as: "User",where: { blocked: "0" },attributes: Config.appData.attributes.managerBadgeAtts,include: [
{
required: false,model: Db.userDevices,where: { userType: "xxxx",fcmId: {$ne: ""} }
}
]
}
],});
其中“Config.appData.attributes.managerBadgeAtts”包含一个子选择。它只是一个带有简单 where 条件的 COUNT(*)。
结果查询(Sequilize 实际从上述调用生成的查询)运行速度非常慢,尽管它只返回 1 个对象,因此我尝试使用 MySQL (5.7) 对其进行分析。结果如下:
*************************** 1. row ***************************
id: 1
select_type: PRIMARY
table: events
partitions: NULL
type: const
possible_keys: PRIMARY,eventId
key: PRIMARY
key_len: 8
ref: const
rows: 1
filtered: 100.00
Extra: NULL
*************************** 2. row ***************************
id: 1
select_type: PRIMARY
table: User
partitions: NULL
type: const
possible_keys: PRIMARY
key: PRIMARY
key_len: 8
ref: const
rows: 1
filtered: 100.00
Extra: NULL
*************************** 3. row ***************************
id: 1
select_type: PRIMARY
table: User->userDevices
partitions: NULL
type: ref
possible_keys: userId
key: userId
key_len: 8
ref: const
rows: 71
filtered: 100.00
Extra: Using where
*************************** 4. row ***************************
id: 2
select_type: SUBQUERY
table: UN1
partitions: NULL
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 480367
filtered: 12.50
Extra: Using where
我们可以看到子选择扫描了大量的行,这就是查询很慢的原因。它也不使用索引。但是,我尝试添加将行数减少到 60 000 的索引,但这并没有解决任何问题。奇怪的是,它只会使查询更慢。
这是我知之甚少的遗留代码。有没有更好的方法来编写 Sequilize 调用来避免这种情况?我该如何优化?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。