简体   繁体   English

单个查询从多个表中收集数据

[英]Single query to collect data from multiple tables

I have a problem collecting data from an SQL database that I designed. 我从设计的SQL数据库收集数据时遇到问题。

This is a table of questions of different types, each type has it's own table with different columns and has the questionid as a foreign key that referenced this table as seen below. 这是一个不同类型的问题的表,每种类型都有自己的表,该表具有不同的列,并且questionid作为引用此表的外键,如下所示。

 Column   |          Type          | Modifiers
------------+------------------------+-----------
 questionid | integer                | not null
 header     | character varying(500) |
Indexes:
    "quizquestion_pkey" PRIMARY KEY, btree (questionid)
Referenced by:
    TABLE "matchingpairs" CONSTRAINT "matchingpairs_questionid_fkey" FOREIGN KEY (questionid) REFERENCES quizquestion(questionid)
    TABLE "mcqchoices" CONSTRAINT "mcqchoices_questionid_fkey" FOREIGN KEY (questionid) REFERENCES quizquestion(questionid)
    TABLE "questionsinquiz" CONSTRAINT "questionsinquiz_questionid_fkey" FOREIGN KEY (questionid) REFERENCES quizquestion(questionid)
    TABLE "truefalsequestion" CONSTRAINT "truefalsequestion_questionid_fkey" FOREIGN KEY (questionid) REFERENCES quizquestion(questionid
)

I have another table that keeps up which question belongs to which quiz using also the questionid 我还有另一个表,也使用questionid保持哪个问题属于哪个测验

   Column   |  Type   | Modifiers
------------+---------+-----------
 quizid     | integer | not null
 questionid | integer | not null
 index      | integer |
Indexes:
    "questionsinquiz_pkey" PRIMARY KEY, btree (quizid, questionid)
Foreign-key constraints:
    "questionsinquiz_questionid_fkey" FOREIGN KEY (questionid) REFERENCES quizquestion(questionid)
    "questionsinquiz_quizid_fkey" FOREIGN KEY (quizid) REFERENCES quiz(quizid)

Is there a way to collect all the different questions in one query or do I have to query on every question type, or is there something different that I can change in the database table design. 有没有一种方法可以在一个查询中收集所有不同的问题,或者我必须对每种问题类型进行查询,或者是否可以在数据库表设计中进行其他更改。

Based on your description, you can use Postgres inheritance. 根据您的描述,您可以使用Postgres继承。 This is a facility where tables can be related to each other. 这是表格可以相互关联的功能。 The place to start learning about it is in the documentation . 文档中可以开始学习它。

Using inheritance, you would have a parent table called questions which defines questionId and other related columns. 使用继承,您将拥有一个称为questions的父表,该表定义了questionId和其他相关列。 Then you can define multiple other tables such as matchingPairsQuestions which inherit from questions . 然后,您可以定义多个其他表,例如matchingPairsQuestions ,它们继承自questions Queries and foreign keys can then refer either to the individual "children" tables or to all of them as a single set. 然后,查询和外键可以引用单个“子级”表,也可以将它们全部作为一个集合引用。

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

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