【发布时间】:2022-01-20 16:06:34
【问题描述】:
我正在构建一个基于 Laravel 作为 API 的“广告”网站,其中包含动态高级搜索。
广告可以有多个属性,用户可以进行高级搜索,但是如果用户检查了这么多要过滤的属性并且查询变得很慢,那么它会导致这么多的子查询,任何关于比这个更好的查询的建议。
select
*
from
`ads`
where
`ads`.`id` in (
select
`ad_attributes`.`ad_id`
from
`ad_attributes`
where
`attribute_id` = 32
and `value` in ('odio', 'quos', 'dignissimos', 'dolorem', 'qui')
)
and `ads`.`id` in (
select
`ad_attributes`.`ad_id`
from
`ad_attributes`
where
`attribute_id` = 171
and `value` in ('itaque', 'non', 'dolor', 'laborum')
)
and `ads`.`id` in (
select
`ad_attributes`.`ad_id`
from
`ad_attributes`
where
`attribute_id` = 111
and `value` in ('quia', 'non', 'nam', 'molestias')
)
and `ads`.`id` in (
select
`ad_attributes`.`ad_id`
from
`ad_attributes`
where
`attribute_id` = 144
and `value` in ('delectus', 'nam', 'exercitationem', 'sit')
)
and `ads`.`id` in (
select
`ad_attributes`.`ad_id`
from
`ad_attributes`
where
`attribute_id` = 160
and `value` in ('repellat', 'fugit', 'quaerat', 'vero')
)
and `ads`.`id` in (
select
`ad_attributes`.`ad_id`
from
`ad_attributes`
where
`attribute_id` = 176
and `value` in ('mollitia', 'voluptates', 'maxime', 'culpa')
)
and `ads`.`id` in (
select
`ad_attributes`.`ad_id`
from
`ad_attributes`
where
`attribute_id` = 177
and `value` in ('necessitatibus', 'id')
)
这是搜索的代码,PS。我正在使用 mpyw/eloquent-has-by-non-dependent-subquery 而不是使用 whereHas,因为它更慢......
->when(!empty($search->attrs), function (Builder $query) use ($search) {
foreach ($search->attrs as $key => $value) {
if (!is_null($value)) {
$query->hasByNonDependentSubquery('adAttributes', function (Builder $q) use ($value, $key, $search) {
$q->where('attribute_id', $key)
->when(is_array($value), fn($q) => $q->whereIn('value', $value))
->when(!is_array($value), fn($q) => $q->where('value', $value));
});
}
}
return $query;
});
我在我的数据库中添加了一些数据,我无法共享所有这些数据,因为它在 Fiddle 上的虚拟种子数据约为 60k [https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=6f00cc71fff716837906c22d46b0c899][1]
【问题讨论】:
-
你说话有多慢?
-
@Savlon 我还没有投入生产,我在 ad_attributes 和 50k 广告中播种了大约 10k 行。没有子查询的查询大约需要 30 毫秒,并且随着我添加更多过滤器和更多子查询,它会不断增长....我发布的查询大约需要 0.5 秒
-
请将问题缩小到 2 个(而不是 7 个)IN,每个只有 2 个选项。然后提供数据样本数据,其中包含您想要的一些行和一些您不想要的行。特别是,提供一些 nnichols 的公式会错误地包含的行。让我们专注于 SQL(假设您可以向后工作到 Elequent)。
标签: mysql laravel eloquent subquery advanced-search