如何在 Postgresql 中建立 parent 和 child table 之间的关系
How to make relationship between parent and child table in Postgresql
我正在学习 postgresql,我在 parent table 和 child table 之间建立关系时遇到了困难。任何帮助将不胜感激。
这是我的 parent table.
Table姓名国家
c_id state No_of_cities Total Population
1 state1 30 60
2 state2 40 70
3 state3 50 80
这是我的 child 的 table 详细信息-
Table 姓名 state1
s_id cities population
1 city1 234
2 city2 345
Table 姓名 state2
s_id cities population
1 city3 544
2 city4 765
Table 姓名 state3
s_id cities population
1 city1 543
2 city5 987
请帮我弄清楚,如何在table之间建立关系,以便我在查询时可以获得准确的数据。
对于所有州的城市,您只需要一个 table:
例如:
Table 名称状态
state no_of_cities population
state1 20 60
state2 30 70
state3 40 80
Table 城市名称
state cities population
state1 city1 234
state1 city2 345
state2 city3 544
state2 city4 765
state3 city1 543
state3 city5 987
然后你可以添加一个外键
ALTER TABLE cities ADD FOREIGN KEY (state) REFERENCES states (state);
但首先您必须设置状态主键
ALTER TABLE states ADD PRIMARY KEY (state)
或者(如果你想要一个整数 id 作为 pk)添加一个唯一键:
ALTER TABLE states ADD UNIQUE (state)
我正在学习 postgresql,我在 parent table 和 child table 之间建立关系时遇到了困难。任何帮助将不胜感激。
这是我的 parent table.
Table姓名国家
c_id state No_of_cities Total Population
1 state1 30 60
2 state2 40 70
3 state3 50 80
这是我的 child 的 table 详细信息-
Table 姓名 state1
s_id cities population
1 city1 234
2 city2 345
Table 姓名 state2
s_id cities population
1 city3 544
2 city4 765
Table 姓名 state3
s_id cities population
1 city1 543
2 city5 987
请帮我弄清楚,如何在table之间建立关系,以便我在查询时可以获得准确的数据。
对于所有州的城市,您只需要一个 table:
例如:
Table 名称状态
state no_of_cities population
state1 20 60
state2 30 70
state3 40 80
Table 城市名称
state cities population
state1 city1 234
state1 city2 345
state2 city3 544
state2 city4 765
state3 city1 543
state3 city5 987
然后你可以添加一个外键
ALTER TABLE cities ADD FOREIGN KEY (state) REFERENCES states (state);
但首先您必须设置状态主键
ALTER TABLE states ADD PRIMARY KEY (state)
或者(如果你想要一个整数 id 作为 pk)添加一个唯一键:
ALTER TABLE states ADD UNIQUE (state)