使用内部联接语句创建sql视图

时间:2014-10-05 01:45:03

标签: mysql sql view create-view

我正在尝试使用内部联接语句创建一个从2个表中获取信息的SQL视图,但我一直收到一个我无法弄清楚的错误。我试图创建的视图语句采用名字,姓氏,然后是pid(用于链接表格),然后只显示体重超过140磅的人。当我尝试在psql中运行我的sql文件时,我一直收到错误。我得到的错误是

\i letsdoit.sql
output #1
psql:letsdoit.sql:7: ERROR:  column reference "pid" is ambiguous
LINE 2: SELECT pid,fname, lnam

我的代码是

 \echo output #1
CREATE VIEW weight AS
SELECT a.pid, a.fname, a.lname
FROM letsdoit.person as a
INNER JOIN letsdoit.body_composition as b
ON a.pid = b.pid
WHERE (b.weight>140);

我正在使用的两个表是

                                  Table "letsdoit.person"
 Column |         Type          |                      Modifiers                      
 --------+-----------------------+---------------------------------------------------
 pid    | integer               | not null default nextval('person_pid_seq'::regclass)
 uid    | integer               | 
 fname  | character varying(25) | not null
 lname  | character varying(25) | not null
 Indexes
"person_pkey" PRIMARY KEY, btree (pid)
 Foreign-key constraints:
"person_uid_fkey" FOREIGN KEY (uid) REFERENCES university(uid) ON DELETE CASCADE
Referenced by:
TABLE "body_composition" CONSTRAINT "body_composition_pid_fkey" FOREIGN KEY (pid
) REFERENCES person(pid) ON DELETE CASCADE
TABLE "participated_in" CONSTRAINT "participated_in_pid_fkey" FOREIGN KEY (pid) 
REFERENCES person(pid)

Table "letsdoit.body_composition"
Column |  Type   | Modifiers 
--------+---------+-----------
pid    | integer | not null
height | integer | not null
weight | integer | not null
age    | integer | not null
Indexes:
"body_composition_pkey" PRIMARY KEY, btree (pid)
Foreign-key constraints:
"body_composition_pid_fkey" FOREIGN KEY (pid) REFERENCES person(pid) ON DELETE CASCADE

1 个答案:

答案 0 :(得分:1)

您需要指定您要查找的pid!

像这样替换:

SELECT a.pid, a.fname, a.lname
FROM letsdoit.person as a
INNER JOIN letsdoit.body_composition as b
ON a.pid = b.pid
WHERE (b.weight>140);