2012-02-08 57 views
0

我正在爲學校項目編寫一個數據庫。我在xampp上使用MySQL並試圖將此表添加到我的數據庫。進出口仍然不是100%我的SQL語法和那裏有此錯誤,我似乎無法TI弄清楚:這個create table語句有什麼問題?

CREATE TABLE photoDB(
    U_id INT UNSIGNED NOT NULL FOREIGN KEY REFERENCES userDB(U_id), 
    P_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, 
    C_id INT UNSIGNED NOT NULL FOREIGN KEY REFERENCES table_comments(C_id), 

    PhotoName VARCHAR(50), 
    Description TEXT NOT NULL, 
    File VARCHAR, 
    Views BIGINT UNSIGNED, 
    Rep DOUBLE (100000, 2), 
    UploadDate DATETIME, 
    EditDate DATETIME, 
    EditVersion INT UNSIGNED, 
    LatestEditVerion INT UNSIGNED 

    ); 

林得衆表我試着去創造的同樣的問題。

繼承人的錯誤消息:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FOREIGN KEY REFERENCES userDB(U_id), P_id INT UNSIGNED NOT NULL AUTO_INCREMENT ' at line 2 

在此先感謝

+0

什麼是錯誤信息? – John3136 2012-02-08 02:23:07

+0

添加了錯誤消息 – 2012-02-08 02:28:00

+0

錯誤可能是由於沒有創建所需的表userDB和table_comments而導致的嗎? Mysql是否要求被引用的表已經存在以便引用表在其中包含語句? – 2012-02-08 02:40:11

回答

3

以前的答案是正確的。你也有其他問題(例如,你不能有一個DOUBLE那麼大;最大= 255)。

你有問題,男人。

下面是一個簡單的例子,也許你可以擴展。它有兩個表格,它們之間有多對多的關係。連接表有兩個外鍵。它在MySQL中工作 - 我剛剛創建了一個數據庫並添加了這些表。

use stackoverflow; 

create table if not exists stackoverflow.product 
(
    product_id int not null auto_increment, 
    name varchar(80) not null, 
    primary key(product_id) 
); 

create table if not exists stackoverflow.category 
(
    category_id int not null auto_increment, 
    name varchar(80) not null, 
    primary key(category_id) 
); 

create table if not exists stackoverflow.product_category 
(
    product_id int, 
    category_id int, 
    primary key(product_id, category_id), 
    constraint product_id_fkey 
     foreign key(product_id) references product(product_id) 
     on delete cascade 
     on update no action, 
    constraint category_id_fkey 
     foreign key(category_id) references category(category_id) 
     on delete cascade 
     on update no action 
); 

insert into stackoverflow.product(name) values('teddy bear'); 
insert into stackoverflow.category(name) values('toy'); 
insert into stackoverflow.product_category 
    select p.product_id, c.category_id from product as p, category as c 
    where p.name = 'teddy bear' and c.name = 'toy'; 
+0

IVe編輯表格來聲明關鍵字列然後聲明列作爲主要ID(不知道我是否描述了這個權利)。與使用主表中的外鍵相比,使用連接表背後的主要想法是什麼? – 2012-02-08 03:17:20

+0

這個例子中的外鍵是對的:這是一個多對多的關係,就像我說的。如果產品只能屬於一個類別,則產品表中的外鍵將指向其類別。 – duffymo 2012-02-08 10:11:53

0

你需要一個逗號,在這條線

EditVersion INT UNSIGNED結束,

+0

你確定OP需要','在最後? **再次閱讀錯誤消息** – 2012-02-08 02:47:10

0

您需要在昏迷關鍵字無符號的結尾。

+0

您確定OP需要','在最後? **再次閱讀錯誤消息** – 2012-02-08 02:46:22

+1

沒有人需要[昏迷](http://en.wikipedia.org/wiki/Coma)!也許[逗號](http://en.wikipedia.org/wiki/Comma)的意圖是? ;) – musefan 2012-02-08 08:45:22

0
FOREIGN KEY( C_id) REFERENCES table_comments(C_id), 
FOREIGN KEY(U_id) REFERENCES userDB (U_id), 

嘗試重寫你的外鍵這樣