【问题标题】:SQL Create view statement using WITH keywordSQL 使用 WITH 关键字创建视图语句
【发布时间】:2014-10-05 20:42:57
【问题描述】:

我在用 SQL 编写此 Create view 语句时遇到问题。我想从前往科罗拉多大学 (uid = 2) 的人的表中获取 personID、名字和姓氏。然后我想使用 WITH 子句将此表与我的 body_composition 表结合起来,并打印出 body_composition 表中的所有内容。这是我正在查询的确切定义。

首先,编写一个返回人的 id (pid)、名字的查询 (fname) 和姓氏 (lname) 来自所有来自 去科罗拉多大学的人。然后,将该查询放入 WITH 子句并将其用作公用表表达式 (CTE) 来组合 身体成分表的结果通过内连接得到 参加大学的人的身体成分 科罗拉多州。

我尝试运行我的创建视图语句,但出现此错误

错误:“what”处或附近的语法错误第 7 行:WITH what.body_composition as c

这是我创建视图语句的代码以及我正在使用的表。

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

【问题讨论】:

  • 您真正使用的是什么数据库? MySQL 不支持with
  • @GordonLinoff 我正在使用 psql
  • 家庭作业?此人发布了几乎相同的内容:stackoverflow.com/q/26207028/398670

标签: sql view psql create-view


【解决方案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(基于我假设您使用的基于 psql 标签的 Postgres)。

【讨论】:

    猜你喜欢
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-29
    • 1970-01-01
    • 2014-05-08
    • 2023-03-08
    相关资源
    最近更新 更多