考虑以下查询来获取计数:
查询A
SELECT
COUNT(*)
FROM
"user_notifications"
WHERE
"user_notifications"."source_id" = 5196
AND "user_notifications"."source_type" = 'MassGifting'
AND "user_notifications"."status" = 'sent'
AND "user_notifications"."read_at" IS NULL
查询B. 它也在同一个表上,只是where子句略有不同,试图根据状态检查通知的声音,如果它们是基于source_id&读取的话。 SOURCE_TYPE:
SELECT
COUNT(*)
FROM
"user_notifications"
WHERE
"user_notifications"."source_id" = 5196
AND "user_notifications"."source_type" = 'MassGifting'
AND (
"user_notifications"."read_at" IS NOT NULL
)
执行细节: 所用时间:5-6秒。总共需要大约30-60秒来执行这两个查询&在我们的网站上呈现报告。
我想知道我们可以加快这个速度的方式是什么?
答案 0 :(得分:0)
尝试以下查询,让我知道需要多长时间?
它应该为您提供1个表扫描中的查询结果。
SELECT
SUM(case when
"user_notifications"."status" = 'sent'
AND "user_notifications"."read_at" IS NULL
then 1 else 0 end) as Result1,
SUM(case when
"user_notifications"."read_at" IS NOT NULL
then 1 else 0 end) as Result2,
FROM
"user_notifications"
WHERE
"user_notifications"."source_id" = 5196
AND "user_notifications"."source_type" = 'MassGifting'
如果我做了一个错误的假设请发表评论,我会重新调整我的答案。