2014-10-05 767 views
0

我在使用SQL创建视图语句时遇到问题。我想从科罗拉多大学(uid = 2)的人那里得到personID,名字和姓氏。然后,我想使用WITH子句将此表与我的body_composition表结合起来,并将body_composition表中的所有内容都打印出来。这是我正在查询的确切定义。SQL使用WITH关键字创建视图语句

First, write a query that returns the person’s id (pid), first name (fname) and last name (lname) from all people who are from the people who go to the University of Colorado. Then, place that query in a WITH clause and use it as a common table expression (CTE) to combine the result with the body composition table via an inner join to get the body compositions for people who attend the University of Colorado.

我尝试运行我的CREATE VIEW声明我得到这个错误

ERROR: syntax error at or near "what" LINE 7: WITH what.body_composition as c

这里是我的与我使用的表沿着这条CREATE VIEW语句代码。

CREATE VIEW withclause AS 
SELECT a.pid, a.fname, a.lname 
FROM what.person AS a 
INNER JOIN what.university AS b 
on a.uid = b.uid 
WHERE uid = 2 
WITH what.body_composition AS c 
SELECT * 
FROM what.body_composition; 

下面是建立在对问题的描述,我使用

    Table "what.university" 
Column   |   Type   |      Modifiers       
-----------------+-----------------------+-------------------------------------- 
uid    | integer    | not null default nextval('university_uid_seq'::regclass) 
university_name | character varying(50) | 
city   | character varying(50) | 


Table "what.body_composition" 
Column | Type | Modifiers 
--------+---------+----------- 
pid | integer | not null 
height | integer | not null 
weight | integer | not null 
age | integer | not null 


    Table "what.person" 
Column |   Type   |      Modifiers      
--------+-----------------------+----------------------------------------------- 
pid | integer    | not null default nextval('person_pid_seq'::reg class) 
uid | integer    | 
fname | character varying(25) | not null 
lname | character varying(25) | not null 
+0

你真的在使用哪个数据库? MySQL不支持'with'。 – 2014-10-05 20:53:09

+0

@GordonLinoff我正在使用psql – disciples22 2014-10-05 21:00:19

+0

家庭作业?此人发布了几乎相同的内容:http://stackoverflow.com/q/26207028/398670 – 2014-10-06 01:11:33

回答

1

三个表我敢肯定这是你想要什么:

CREATE VIEW withclause AS 

WITH cte AS (
    SELECT p.pid, p.fname, p.lname 
    FROM what.person as p 
    INNER JOIN what.university as u 
    ON p.uid = u.uid 
    WHERE p.uid = 2 
) 

SELECT cte.pid, cte.fname, cte.lname, c.age, c.height, c.weight 
FROM cte 
INNER JOIN what.body_composition c on c.pid = cte.pid; 

Sample SQL Fiddle(基于Postgres,我假设你使用基于psql标签)。