关联模型的查询效率问题
数据表
pictures
字段 | 类型 | 备注 |
---|---|---|
id | integer | 自增主键 |
url | varchar | 地址 |
extensions | json | 附加信息 |
tags
字段 | 类型 | 备注 |
---|---|---|
id | integer | 自增主键 |
name | varchar | 标签名称 |
taggables
字段 | 类型 | 备注 |
---|---|---|
tag_id | integer | 关联 tag |
taggable_id | integer | 多态关联 |
taggable_type | varchar | 多态关联 |
使用 whereHas
来通过标签筛选时, 如果数据超过20万条查询会变得非常慢(超过1500ms)。
查询语句如下
select
*
from
`pictures`
where
exists (
select
*
from
`tags`
inner join `taggables` on `tags`.`id` = `taggables`.`tag_id`
where
`pictures`.`id` = `taggables`.`taggable_id`
and `taggables`.`taggable_type` = 'pictures'
and `id` = '9'
)
and `pictures`.`deleted_at` is null
order by
`created_at` desc
limit
30 offset 0
用了一个比较笨的解决办法,先从 taggables
表中查出 tag_id = 9
的 taggable_id
, 然后再从 pictures
表中使用 whereIn
查询。
但是有一个问题如果还有其他关联的话,好像没法通过多条语句来查询(因为还需要数据总数构造分页信息)
类似这种情况该如何优化查询语句
推荐文章: