2017-06-13 113 views
0

我刚刚坦白地告诉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

@VaoTsun哦,你会如何使用'reference'关键字?有没有视频或指导我也可以看看 – MonocleBoo

+0

请看看我的答案中的代码 - 有如何使用外键 –

回答

0
这样

CREATE TABLE new_table as SELECT id,... from old_table where id = 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

%#

如果会话用户是数据库超级用户,然后是#,否则是>。 (这个值的扩展可能在一个数据库会话 过程中改变命令SET SESSION认定结果。)

+0

谢谢你的例子,当你添加播放器时,'=#'是什么? – MonocleBoo

+0

更新了答案以反映您的问题。简而言之 - 只是忽略这些 - 当我复制/粘贴时,它们带有'psql'输出 –

相关问题