SQL将所有数据插入到桥接表,(很多)

时间:2018-12-16 22:44:30

标签: sql postgresql many-to-many

我有两个如下表;

X表;

+---+----------+
| id| value    |
+---+----------+
| 1 | x value1 |
+---+----------+
| 2 | x value2 |
+---+----------+
| 3 | x value3 |
+---+----------+

Y表;

+---+----------+
| id| value    |
+---+----------+
| 1 | y value1 |
+---+----------+
| 2 | y value2 |
+---+----------+
| 3 | y value3 |
+---+----------+

然后我创建了新表(x_y表),该表具有x和y表的外键;

我想将彼此相关的所有数据添加到新表中,如下所示; x_y表

+----+------+------+
| id | x_id | y_id |
+----+------+------+
| 1  | 1    | 1    |
+----+------+------+
| 2  | 1    | 2    |
+----+------+------+
| 3  | 1    | 3    |
+----+------+------+
| 4  | 2    | 1    |
+----+------+------+
| 5  | 2    | 2    |
+----+------+------+
| 6  | 2    | 3    |
+----+------+------+
| 7  | 3    | 1    |
+----+------+------+
| 8  | 3    | 2    |
+----+------+------+
| 9  | 3    | 3    |
+----+------+------+

如何在postgresql脚本的第三张表中添加这样的值。

2 个答案:

答案 0 :(得分:2)

这可以通过生成ID的 git stash # stash everything git stash apply # apply the stash, but keep it in the stash (don't pop) git checkout to_keep # discard the stuff you want to keep in your working tree (remember it's in the stash) git stash save "message" # stash the stuff you want to stash git stash pop stash@{1} # apply the first stash, which includes the stuff you wanted to keep and the stuff you wanted to stash git checkout to_stash # discard the stuff you stashed cross join完成。

row_number

答案 1 :(得分:1)

大概新表定义为id作为串行列。如果是这样,您可以通过以下方式插入数据:

insert into x_y (x_id, y_id)
    select x.id, y.id
    from x cross join
         y
    order by x.id, y.id;