我必须在sql中编写一个使用exists命令的create view语句。我尝试在网上查找,但我遇到了一些困难。我尽力编写创建视图文件,但它现在无法正常工作。我知道我需要在我的声明中使用关键字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
答案 0 :(得分:0)
您好使用以下代码并告诉我反馈
创建视图checkuni AS 选择a.university_name,a.city FROM 大学作为一个 什么不存在 (选择p.uid FROM person为p 在哪里p.uid = a.uid)
答案 1 :(得分: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
在某些情况下,您可能需要使用SELECT DISTINCT
,但我想在您的情况下不一定需要。