2010-07-09 60 views
0

我在做什麼錯了?我需要創建外鍵,但CONSTRAINT開頭的代碼在某種程度上是錯誤的,同樣我需要幫助我的觀點我認爲如果子查詢錯了,你能幫助我嗎?簡單的外鍵/創建查看問題

CREATE TABLE dealer(
dealershipId CHAR(10), 
phone CHAR(10), 
dealershipName CHAR(10), 
webAddress char (10), 
street CHAR (10), 
city char (10), 
zip char (5), 
mCapacity INT, 
managerFName CHAR (10), 
managerLName CHAR (10), 
PRIMARY KEY (dealershipId)); 

CREATE TABLE automobiles(
autoId CHAR (4), 
vehiclecode VARCHAR (15), 
manufacturer VARCHAR(15), 
model VARCHAR (20), 
style VARCHAR (5), 
color VARCHAR (10), 
ownership VARCHAR (8), 
PRIMARY KEY (autoId) 
CONSTRAINT fkHasRep FOREIGN KEY (dealershipId) 
REFERENCE dealer(dealershipId) ON DELETE RESTRICT 
); 

--7. 
CREATE VIEW division AS 
SELECT dealershipName, webAddress, phone 
FROM dealer 
WHERE dealershipId IN 
(SELECT manufacturer, model, style, ownership 
FROM automobiles); 

--8. 
SELECT phone, manufacturer, model 
FROM division; 

回答

1

你錯過主KED &外鍵之間的逗號:

CREATE TABLE automobiles(
autoId CHAR (4), 
vehiclecode VARCHAR (15), 
manufacturer VARCHAR(15), 
model VARCHAR (20), 
style VARCHAR (5), 
color VARCHAR (10), 
ownership VARCHAR (8), 
PRIMARY KEY (autoId), 
CONSTRAINT fkHasRep FOREIGN KEY (dealershipId) 
REFERENCE dealer(dealershipId) ON DELETE RESTRICT 
); 

MySQL的觀點不允許在視圖子查詢(錯誤#1349) - 在restrictions are documented here。因此,將其轉換爲使用代替連接:

CREATE VIEW division AS 
    SELECT d.dealershipName, d.webAddress, d.phone, a.* 
    FROM DEALER d 
    JOIN AUTOMOBILES a ON d.dealershipid IN (a.manufacturer, 
               a.model, 
               a.style, 
               a.ownership); 
+0

謝謝零件已修復,我也在汽車表中缺少經銷商ID。現在你能幫助我看看嗎? – 2010-07-09 20:09:26

+0

@Michael Quiles:查看更新 – 2010-07-09 20:14:28

+0

,它不起作用,它只會從經銷商表中提取數據,而不會添加汽車表格。 – 2010-07-09 20:24:47

1

我的猜測是,您的汽車表上沒有經銷商標識。

而且,您的視圖不會起作用,因爲您只能在嵌套選擇查詢中包含一個字段。你也可以重寫那個以使用INNER或OUTER JOIN。

+0

這是我應該做的使用子查詢我相信我們在課堂上取得了類似的東西,但沒有進一步解釋。 7.創建包含所選模型中兩個表格的字段的VIEW – 2010-07-09 20:02:12

1

默認的Myisam引擎不支持外鍵。 在CREATE TABLE語句中指定Innodb引擎。

CREATE TABLE dealer(
dealershipId CHAR(10), 
phone CHAR(10), 
dealershipName CHAR(10), 
webAddress char (10), 
street CHAR (10), 
city char (10), 
zip char (5), 
mCapacity INT, 
managerFName CHAR (10), 
managerLName CHAR (10), 
PRIMARY KEY (dealershipId)) ENGINE = Innodb;