2014-10-05 762 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標籤)。