0

我必须在使用存在命令的 sql 中编写一个创建视图语句。我尝试在网上查找它,但我遇到了一些困难。我尽力编写创建视图文件,但它现在无法正常工作。我知道我需要在我的语句中使用关键字 EXIST。我试图创建的声明是

Write a query that shows returns the name and city of the university that has no people in database
that are associated with it.

到目前为止我写的代码是这样的

CREATE VIEW exist AS
SELECT a.university_name, a.city
FROM lab5.university as a
INNER JOIN lab5.person as b
ON a.uid = b.uid
WHERE b.uid  NOT EXIST

我正在使用的表是

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

            Table "table.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
4

2 回答 2

0

嗨使用下面的代码,让我知道反馈

CREATE VIEW checkuni AS SELECT a.university_name, a.city FROM university as a WHERE NOT EXISTS (SELECT p.uid FROM person as p WHERE p.uid = a.uid)

于 2014-10-05T05:06:58.957 回答
0

EXISTS 是一个谓词,因此您的查询应该类似于:

SELECT a.university_name, a.city
FROM lab5.university as a
WHERE NOT EXISTS (
    SELECT 1 
    FROM lab5.person as b
    WHERE a.uid = b.uid
);

你也可以使用外连接和IS NULL谓词来表达同样的事情:

SELECT a.university_name, a.city
FROM lab5.university as a
LEFT JOIN lab5.person as b
    ON a.uid = b.uid
WHERE b.uid IS NULL

在某些情况下,您可能需要使用 aSELECT DISTINCT但我想在您的情况下这不是必需的。

于 2014-10-05T05:07:41.240 回答