2014-10-05 37 views
0

我必須在sql中使用一個exist命令編寫一個創建視圖語句。我試着在網上查找,但我有一些困難。我盡我所能寫了創建視圖文件,但它現在還沒有工作。我知道我需要在我的聲明中使用關鍵字EXIST。我想創建的語句是使用EXIST命令創建一個sql視圖語句

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

嗨使用下面的代碼,讓我知道反饋

CREATE VIEW checkuni AS SELECT a.university_name,a.city FROM 大學作爲一個 WHERE NOT EXISTS (SELECT p.uid從一個人如對 WHERE p.uid =一個。 UID)

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 
); 

您也能表達次e。使用外連接和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某些情況下,但我想這不會是必要的,你的情況。