我坦率地说是sql的新手,这是我正在做的一个项目。
我想知道在创建表时是否可以将一个表中的一个列连接到另一个表。我知道显示结果的join
方法,但我希望尽可能地减少代码。
CREATE TABLE players (
id INT PRIMARY KEY, -->code I want connect with table match_record
player_name CHARACTER
);
CREATE TABLE match_records (
(id INT PRIMARY KEY /*FROM players*/), --> the code I want it to be here
winner INT,
loser INT
);
答案 0 :(得分:0)
以这种方式:
CREATE TABLE new_table as SELECT id,... from old_table where id = 1;
答案 1 :(得分:0)
CREATE TABLE players (
id INT not null PRIMARY KEY, -->code I want connect with table match_record
player_name CHARACTER
);
CREATE TABLE match_records (
id INT not null PRIMARY KEY references players(id), --> the code I want it to be here
winner INT,
loser INT
);
这样您就可以限制match_records.id
仅来自players.id
:
t=# insert into match_records select 1,1,0;
ERROR: insert or update on table "match_records" violates foreign key constraint "match_records_id_fkey" DETAIL: Key (id)=(1) is not present in table "players".
所以我添加了玩家:
t=# insert into players(id) values(1),(2);
INSERT 0 2
现在它允许插入:
t=# insert into match_records select 1,1,0;
INSERT 0 1
<强>更新强> https://www.postgresql.org/docs/current/static/app-psql.html#APP-PSQL-PROMPTING
%#
如果会话用户是数据库超级用户,则为#,否则为&gt;。 (此值的扩展可能会在数据库会话期间更改为 SET SESSION AUTHORIZATION命令的结果。)