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

时间:2019-04-25 15:46:23

标签: sql amazon-redshift

比方说,我有一个调查数据架构,我的事实表代表每个响应此调查的人,其中一个维度表具有该调查的所有答案,从事实表中获取所有记录的最有效方法是匹配答案表上的多个条件?

事实表(记录):

| id | name | date | gender |

尺寸表(答案):

| record_id | question_id | value |

我可以为每个问题创建一个新的左联接,但是如果我想找到一个记录可以回答多个问题的记录,这似乎没有什么作用

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);

还有其他选择吗?

3 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,则需要:

   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;

答案 1 :(得分:0)

经过更多的挖掘之后,看来最可扩展和动态的方式是使用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)

答案 2 :(得分:0)

我将对所需的问题/值列表进行硬编码并使用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)
;