postgresql 我得到了与时间戳字段为标志的请求的性能不好?

ryoqjall  于 2023-06-29  发布在  PostgreSQL
关注(0)|答案(1)|浏览(102)

在laravel 8应用程序中,我有一个表定义为2个时间戳字段,不仅用作日期时间值,还用作“发布/未发布”的标志:

Schema::create('news', function (Blueprint $table) {
            $table->id();
            $table->string('title',255);
            ...
            $table->timestamp('published_at')->nullable();
            $table->timestamp('postponed_published_at')->nullable();
            $table->timestamps();

            $table->softDeletes();

    ...
            $table->index(['postponed_published_at', 'published_at', 'title'], 'news_postponed_published_at_published_at_title_index');
        });

我运行请求:

$news = News::query()
    ->whereNull('published_at')
    ->whereRaw("postponed_published_at = '" . $this->day . "' ")
->get();

然后我检查请求的解释:

explain   SELECT *
    FROM "news"
    WHERE "published_at" is null     AND postponed_published_at = '2023-06-24 00:00:00'      AND "news"."deleted_at" is null

Seq Scan on news  (cost=0.00..5.78 rows=1 width=485)
  Filter: ((published_at IS NULL) AND (deleted_at IS NULL) AND (postponed_published_at = '2023-06-24 00:00:00'::timestamp without time zone))

这个扫描结果从性能上看对我来说似乎不太好...可以用一些更好的方法来实现最新版本的mysql/postgres吗?

hsvhsicv

hsvhsicv1#

添加此索引:

INDEX(published_at, deleted_at, postponed_published_at)

列的顺序对于 this 查询无关紧要。让我们看看你的类似查询;可能存在更好的排序。
关于索引创建的更多信息:Index Cookbook,注意IS NULL的优化方式与=类似,但IS NOT NULL的工作方式不同。

相关问题