简体   繁体   English

在同一维度表上从具有多个条件的事实表中选择记录

[英]Select records from fact table with multiple conditionals on the same dimension table

Let's say I have a survey data schema, my fact table represents each person responding this survey, one of the dimension tables has all the answers to the survey, what's the most efficient way to get all the records from the fact table that match multiple conditionals on the answers table? 假设我有一个调查数据模式,我的事实表代表每个响应此调查的人,其中一个维度表具有调查的所有答案,从事实表中获取匹配多个条件的所有记录的最有效方法是什么在答案桌上?

FACT TABLE (records): 事实表(记录):

| id | name | date | gender |

DIMENSION TABLE (answers): 尺寸表(答案):

| record_id | question_id | value |

I could do a new left join for every question, but this seems very inneficient if I want to find a record that answered multiple questions 我可以为每个问题做一个新的左连接,但如果我想找到一个回答多个问题的记录,这似乎非常有用

SELECT * FROM records r 
    left join answers a on r.id = a.record_id 
    left join answers a2 on r.id = a2.record_id 
    where (a.question_id = 1 and a.value = 2) 
    and (a2.question_id = 3 and a2.value = 1);

Any alternative to this? 除此之外的其他选择?

If I understand your question correctly, you need: 如果我理解你的问题,你需要:

   SELECT 
       *
     FROM records r 
LEFT JOIN answers a ON r.id            = a.record_id
                   AND a.question_id   = 1 
                   AND a.value         = 2 
LEFT JOIN answers a2 ON r.id           = a2.record_id 
                    AND a2.question_id = 3 
                    AND a2.value       = 1;

After some more digging it looks like the most scalable and dynamic way is using EXISTS 经过一番挖掘,看起来最具可扩展性和动态性的方式就是使用EXISTS

SELECT * FROM records r  WHERE 
  EXISTS (SELECT * FROM answers WHERE record_id = r.id AND question_id = 1 AND value = 1) AND
  EXISTS (SELECT * FROM answers WHERE record_id = r.id AND question_id = 3 AND value = 1)

I would hardcode the list of questions/values you want and use join: 我会硬编码你想要的问题/值列表并使用join:

with
 question_filter as (
    select 1 as question_id, 2 as value
    union select 3, 1
)
select *
from records r
join answers a
on r.id=a.record_id
join question_filter
using (question_id,value)
;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM