从两个不同的SELECT查询中插入一个包含两个字段的行?

时间:2015-09-23 07:45:59

标签: sql postgresql

我有以下PostgreSQL数据库:

Database

现在,我无法形成插入语句。我想将行插入def comment(self, obj): return '{{{}|truncatewords:10}}'.format(obj.comment) comment.allow_tags = True comment.short_description = "Comment" ,以便每个DiscussionParticipation都有两个条目:

  • 拥有相关Discussion

    User一个
  • 拥有与Activity

    相关的User的{​​{1}}

例如,如果有以下条目:

Response

换句话说:用户'Adam'创建了一个用户'Bill'已创建响应的活动。该活动存在相关讨论。

现在,我想将这两行添加到Activity表中:

Discussion:
id: 1 | Activity_id: 1

Activity:
id: 1 | User_id: 1

Response:
id: 1 | Activity_id: 1 | User_id: 2

User:
id: 1 | username: Adam
id: 2 | username: Bill

如何形成此INSERT?

1 个答案:

答案 0 :(得分:0)

用户列表可以参与讨论活动联盟用户列表可以参与讨论的响应。

insert into DiscussionParticipation (User_id, Discussion_id) (

    select a.User_id as User_id, d.id as Discussion_id
    from Discussion d
    inner join Activity a on (a.id = d.Activity_id)

    union

    select r.User_id as User_id, d.id as Discussion_id
    from Discussion d
    inner join Response r on (r.Activity_id = d.Activity_id)

);