2016-10-14 50 views
2

我有兩個表的球員和比賽:我的PSQL查看錶有什麼問題?

CREATE TABLE player(
id serial PRIMARY KEY NOT NULL, 
name varchar(255) NOT NULL 
); 

CREATE TABLE match(
id serial PRIMARY KEY, 
winner serial REFERENCES player(id) NOT NULL, 
loser serial REFERENCES player(id) NOT NULL CHECK (loser != winner) 
); 

CREATE SEQUENCE playerid_sequence 
start 1 
increment 1; 

CREATE SEQUENCE matchid_sequence 
start 1 
increment 1; 

我希望創建一個連接兩個表的視圖表:

CREATE VIEW matchplayers AS 
SELECT winner.name, loser.name, m.id 
from player winner, player loser, match m 
WHERE m.winner = winner.id AND m.loser = loser.id; 

但它返回的是「名」已經提到了錯誤不止一次。相當缺乏經驗,SQL

+0

您需要爲'name'列添加一個別名(當您沒有提供一個時,架構不會出現在Postgres爲您生成的名稱中)。使用'SELECT winner.name AS winner_name,loser.name AS loser_name,...'。 – Marth

回答

5

嘗試

CREATE VIEW matchplayers AS 
SELECT winner.name as winner_name, loser.name as loser_name, m.id 
from player winner, player loser, match m 
WHERE m.winner = winner.id AND m.loser = loser.id; 

得到的觀點的明確列名。

+0

你擊敗了我0.5秒:http://sqlfiddle.com/#!15/01edf。好工作。 – arcee123

+0

這句話的意思是「從玩家贏家,玩家輸家嗎?」。我通常使用'tableA,tableB'。謝謝 – AlainIb

+0

@AlainIb - 'match'連接兩次到'player'獲得兩個不同的行(一個是贏家,另一個是失敗者)。 – klin