2016-03-13 104 views
0

當我執行此查詢:錯誤:關係 「學生」 已經存在

CREATE TABLE public.students (
    id INTEGER PRIMARY KEY NOT NULL DEFAULT NEXTVAL('students_id_seq'::regclass), 
    first_name CHARACTER VARYING(20) NOT NULL, 
    last_name CHARACTER VARYING(20) NOT NULL, 
    major CHARACTER VARYING(20) NOT NULL 
); 
CREATE UNIQUE INDEX "Students_ID_uindex" ON students USING BTREE (id); 

SELECT * FROM public.students; 

我收到以下錯誤:

[2016-03-12 22:16:54] Run postgres.public.students [PostgreSQL - [email protected]] 
[2016-03-12 22:16:54] Connecting TO PostgreSQL - [email protected] 
CREATE TABLE public.students (
    id INTEGER PRIMARY KEY NOT NULL DEFAULT NEXTVAL('students_id_seq'::regclass), 
    first_name CHARACTER VARYING(20) NOT NULL, 
    last_name CHARACTER VARYING(20) NOT NULL, 
    major CHARACTER VARYING(20) NOT NULL 
) 
[2016-03-12 22:16:54] [42P07] ERROR: relation "students" already EXISTS 
CREATE UNIQUE INDEX "Students_ID_uindex" ON students USING BTREE (id) 
[2016-03-12 22:16:54] [42P07] ERROR: relation "Students_ID_uindex" already EXISTS 
SELECT * FROM public.students 
[2016-03-12 22:16:54] Executed IN 14ms ms 

[2016-03-12 22:16:54] Summary: 3 OF 3 statements executed, 2 failed IN 68ms (338 symbols IN file) 

我已經使用由表DataGrip產生: enter image description here

任何想法我做錯了什麼?

enter image description here

更新:只是爲了澄清我的問題,當我第一次使用新的表名運行的代碼,我現在得到的錯誤,但是當我再次運行它,我得到上述錯誤。這怎麼解決?

enter image description here

回答

4

不能創建具有相同名稱的多個表 - 這樣的語句CREATE應該失敗,如果有同名的表了。

您可以運行語句DROP TABLE之前 - 但注意! - 它會刪除所有數據表,並且撤銷是不可能的。

DROP TABLE IF EXISTS foo; 
CREATE TABLE foo(a int); 

CREATE TABLE IF NOT EXISTS foo(a int); 
:第二種方法是在 CREATE語句中使用條款 IF NOT EXISTS
相關問題