【发布时间】:2020-02-20 06:26:19
【问题描述】:
使用 PostgreSQL 数据库:
我有一个调查应用程序,用户可以在其中输入活动并回答有关他们活动的问题。调查本身称为RECALLS_T,输入的事件是EVENTS_T,答案是ANSWERS_T。答案是针对提供的活动问题,存储在 ACTIVITY_QUESTIONS_T 中,由 Lookup (LOOKUP_T) 映射。
然后我需要运行一个基于事件的报告,其中每一行都是来自EVENTS_T 的每个召回 的事件(所有事件合并为所有召回)。但是,该报告中的某些列需要为某些答案指明一个值,否则这些单元格为 NULL。所以这是一个表格报告。
示例(先是简单的平面内容,然后是复杂的表格内容):
RecallID | RecallDate | Event |..| WalkAlone | WalkWithPartner |..| ExerciseAtGym
256 | 10-01-19 | Exrcs |..| NULL | NULL |..| yes
256 | 10-01-19 | Walk |..| yes | NULL |..| NULL
256 | 10-01-19 | Eat |..| NULL | NULL |..| NULL
257 | 10-01-19 | Exrcs |..| NULL | NULL |..| yes
我的 SQL 对基于答案的列表列有内部选择,如下所示:
select
-- Easy flat stuff first
r.id as recallid, r.recall_date as recalldate, ... ,
-- Example of Tabulated Columns:
(select l.description from answers_t ans, activity_questions_t aq, lookup_t l
where l.id=aq.answer_choice_id and aq.question_id=13
and aq.id=ans.activity_question_id and aq.activity_id=27 and ans.event_id=e.id)
as transportationotherintensity,
(select l.description from answers_t ans, activity_questions_t aq, lookup_t l
where l.id=66 and l.id=aq.answer_choice_id and aq.question_id=14
and aq.id=ans.activity_question_id and ans.event_id=e.id)
as commutework,
(select l.description from answers_t ans, activity_questions_t aq, lookup_t l
where l.id=67 and l.id=aq.answer_choice_id and aq.question_id=14 and aq.id=ans.activity_question_id and ans.event_id=e.id)
as commuteschool,
(select l.description from answers_t ans, activity_questions_t aq, lookup_t l
where l.id=95 and l.id=aq.answer_choice_id and aq.question_id=14 and aq.id=ans.activity_question_id and ans.event_id=e.id)
as dropoffpickup,
SQL 工作正常,报表被渲染,但性能很差。我证实它是成比例的糟糕:没有可以修复它的特定项目的灵丹妙药。每个内部选择都会导致糟糕的表现。 1000 行的结果集需要 15 秒,但应该不会超过 2-3 秒。
请注意,这些索引已经存在:
-
ANSWERS_T: 在ACTIVITY_QUESTION_ID,EVENT_ID -
EVENTS_T: 在RECALL_ID -
ACTIVITY_QUESTIONS_T:在ACTIVITY_ID,QUESTION_ID,ANSWER_CHOICE_ID
这些内部选择是不是我做错了什么?
【问题讨论】:
标签: sql postgresql hibernate jpa