根据另一个表中存储的条件选择唯一行

问题描述 投票:0回答:1

我想根据从数据库中获取的条件选择行。表结构如下所述。

# Questions Table: 
╔════════════╦═══════════════╦════════╗
║ id         ║ chapter_id    ║ weight ║
╠════════════╬═══════════════╬════════╣
║ question-1 ║ first         ║ 1      ║
║ question-2 ║ second        ║ 1      ║
║ question-3 ║ third         ║ 1      ║
║ question-4 ║ first         ║ 2      ║
║ question-5 ║ third         ║ 2      ║
╚════════════╩═══════════════╩════════╝
# Patterns Tables
╔════╦═════════════════╦════════╗
║ id ║ question_number ║ weight ║
╠════╬═════════════════╬════════╣
║ p1 ║ 1               ║ 1      ║
║ p2 ║ 2               ║ 1      ║
║ p3 ║ 3               ║ 1      ║
║ p4 ║ 4               ║ 2      ║
║ p5 ║ 5               ║ 2      ║
╚════╩═════════════════╩════════╝
# Patterns to SubChapters 
╔════════════╦═══════════════╗
║ pattern_id ║ chapter_id    ║
╠════════════╬═══════════════╣
║ p1         ║ first         ║
║ p2         ║ second        ║
║ p3         ║ third         ║
║ p4         ║ first         ║
║ p4         ║ second        ║
║ p5         ║ second        ║
║ p5         ║ third         ║
╚════════════╩═══════════════╝

现在我想为每个匹配模式选择一个独特的问题

所需输出:

╔════════════╦═════════════════╦═════════════╗
║ pattern_id ║ question_number ║ question_id ║
╠════════════╬═════════════════╬═════════════╣
║ p1         ║ 1               ║ question-1  ║
║ p2         ║ 2               ║ question-2  ║
║ p3         ║ 3               ║ question-3  ║
║ p4         ║ 4               ║ question-4  ║
║ p5         ║ 6               ║ question-5  ║
╚════════════╩═════════════════╩═════════════╝

// p1 can be from first chapter with weight = 1 (i.e. question-1)
// p2 can only be second chapter with weight = 1 (i.e. question-2)
// p3 can be from third chapter with weight = 1 (i.e. question-3)
// p4 can be from first with weight = 2 (question-4)
// p5 can be from third with weight = 2 (question-5)

// similarly if there are multiple options, it should choose randomly from one of them.

// Weight are also considered a condition and the generated question_id column should be unique

我对 sql 数据库很陌生,仍在学习中,请让我知道可以采取什么措施来解决此类问题?我正在使用 postgres 和 drizzle orm 来进行我的测验应用程序。

目前,我已经通过 100 个单独的顺序查询来解决这种情况,这需要更长的时间,并且不适合在云函数中运行。 当前解决方案

database postgresql performance drizzle
1个回答
0
投票

我无法帮助您完成确切的查询,但我建议您将任务分成两部分:

  1. 进行一个查询,连接所有具有重复问题的表。
  2. 从结果中选择独特的问题。

对于第一部分,您可以使用

JOIN
表达式。例如,您可以使用问题编号/id 将模式连接到问题。据我了解,您还想使用章节 ID 将问题与“Patterns to SubChapters”表连接起来。您可以使用
UNION
运算符将两个结果合并到一张表中。

完成此操作后,您应该有一个包含重复问题的表格。您可以根据您的标准使用

SELECT DISTINCT ON
选择独特的问题。您将指定所需的唯一列 (question_id) 以及如何在重复项中选择一行 (
ORDER BY ...
)

希望有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.