【发布时间】:2021-06-20 02:35:42
【问题描述】:
我有两个表,question(question_id) 和 question_exclusion(question_type, question_sub_type, question_id)
如果我指定 question_type 和 question_sub_type,我就能做到。
SELECT *
FROM question AS t1
LEFT JOIN (SELECT t.question_id
FROM question_exclusion as t
WHERE t.question_type = 'A'
AND t.question_sub_type = 'A_1') AS t2
ON t1.question_id = t2.question_id
WHERE t2.question_id is null;
但我想要实现的是在单个查询中获取所有带有 questions_ids 的问题,以获取所有可能的 question_type 和 questions_sub_type
question_type 和 questions_sub_type 是动态参数,在查询执行之前我不知道确切的值
更新 1:
实际数据:
表:question
question_id|
42
10
2
36
49
表:question_exclusion
question_type|question_sub_type|question_id|
A | A_1 | 42
A | A_1 | 10
A | A_2 | 10
B | B_1 | 36
C | null | 2
预期结果:
question_type|question_sub_type|question_id
A | A_1 | 2
A | A_1 | 36
A | A_1 | 49
A | A_2 | 42
A | A_2 | 2
A | A_2 | 36
A | A_2 | 49
B | B_1 | 42
B | B_1 | 10
B | B_1 | 2
B | B_1 | 49
C | null | 42
C | null | 10
C | null | 36
C | null | 49
它就像每个类型和子类型组合的列表列表 考虑到排除表
例如:
type=A, sub_type=A_1 -> (select * from questions) - (select * from question_exclusion where type='A' and sub_type='A_1')
+
type=A, sub_type=A_2 -> (select * from questions) - (select * from question_exclusion where type='A' and sub_type='A_2')
+
type=B, sub_type=B_1 -> (select * from questions) - (select * from question_exclusion where type='B' and sub_type='B_2')
当然我可以查询所有不同的(类型,子类型)并通过结合联合进行另一个查询
SELECT *
FROM question AS t1
LEFT JOIN (SELECT t.question_id
FROM question_exclusion as t
WHERE t.question_type = 'A'
AND t.question_sub_type = 'A_1') AS t2
ON t1.question_id = t2.question_id
WHERE t2.question_id is null
UNION
SELECT *
FROM question AS t1
LEFT JOIN (SELECT t.question_id
FROM question_exclusion as t
WHERE t.question_type = 'B'
AND t.question_sub_type = 'B_1') AS t2
ON t1.question_id = t2.question_id
WHERE t2.question_id is null
...
...
N times for all type and sub_type
我正在寻找另一种在单个查询中执行此操作的可靠方法
【问题讨论】:
-
请提供样本数据和期望的结果。您的数据模型也确实令人困惑。为什么
user有一个question_id列?如果用户有多个问题怎么办?有questions表吗?为什么“排除”表有类型和子类型? -
抱歉造成混淆,刚刚编辑并删除了用户前缀。这只是一个问题和问题排除表
-
现在,什么这是
id?回答此问题的用户是user_id吗?表和列的适当描述名称可以帮助我们理解。 (如果是联结表,user_question可能是更具描述性的名称) -
我的错,删除了所有不必要的用户、ID等,只留下了需要的列
-
您有针对特定类型/子类型的单一排除问题吗? question_exclusion 表中是否有效行:(A | A_1 | 42), (A | A_1 | 43)
标签: sql postgresql