【问题标题】:How to copy/insert multiple rows of data to implement many to many relationship in postgres如何复制/插入多行数据以在postgres中实现多对多关系
【发布时间】:2018-05-15 18:46:31
【问题描述】:

我在 Postgres 中有以下表格:问题、响应和 question_response。问题和回答之间存在多对多的关系。

questions.sql

CREATE TABLE questions( 
    id BIGSERIAL PRIMARY KEY,
    question VARCHAR(255)
);

respones.sql

CREATE TABLE responses( 
    id BIGSERIAL PRIMARY KEY,
    response VARCHAR(255)
);

question_respone.sql #

CREATE TABLE question_response(
    question_id bigint REFERENCES questions ON DELETE CASCADE,
    response_id bigint REFERENCES responses ON DELETE CASCADE,
    PRIMARY KEY ( question_id, response_id)
);

问题表中有以下数据

id | question
 1   Rate the effectiveness of the program?
 2   Rate the ease of learning?
 3   Rate the duration ?
 .....
// there are a list of 20 questions 

在响应表中

id | response
 100   Poor
 200   Average
 300   Good
 400   Excellent

如何在 Postgres 中编写函数查询以在 question_response 表中插入以下数据。

question_id | response_id

         1   100
         1   200
         1   300
         1   400
         2   100
         2   200
         2   300
         2   400
         3   100
         3   200
         3   300
         3   400
         4   100
         4   200
         4   300
         4   400
        ......... etc for all 20 questions

【问题讨论】:

    标签: sql postgresql foreign-keys sql-insert


    【解决方案1】:
    insert  into question_response
    select  q.id
    ,       r.id
    from    responses r
    cross join
            questions q
    

    Example at SQL Fiddle.

    【讨论】:

    • @Andomar 感谢您的帮助。我试图通过在 question_response 表中引用它们的 ID 来提取问题和响应,但出现以下错误。不知道如果我在这里遗漏了什么。 select q1.question, r1.response from questions q1, responses r1, question_reponse qr where q1.id = qr.question_id and r1.id = qr.response_id group by q1.question; 错误:关系“question_reponse”不存在第 1 行:...on,r1.response 来自问题 q1,响应 r1,question_r...
    • 错误表示关系(表的另一个名称)不存在。但是在您的问题中,该关系被命名为question_response...您确定它在数据库中具有该名称吗?
    • @Andomar 我想我明白了。查询中有错字。对此感到抱歉
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 2020-03-23
    • 2018-12-29
    • 2018-05-26
    • 2019-04-10
    相关资源
    最近更新 更多