2014-01-09 138 views
0

我是SQL的新手,我想在兩個表之間創建一個One-To-Many關係。 我有以下的數據庫查詢這兩個表:SQL一對多關係

CREATE TABLE Customers 
(
    CustomerId INT NOT NULL AUTO_INCREMENT, 
    FirstName VARCHAR(255) NOT NULL, 
    LastName VARCHAR(255) NOT NULL, 
    Email VARCHAR(255) NOT NULL, 
    Address VARCHAR(255) NOT NULL, 
    PRIMARY KEY(CustomerId) 
); 

CREATE TABLE Orders 
(
    OrderId INT NOT NULL AUTO_INCREMENT, 
    Date DATE NOT NULL, 
    Quantity INT NOT NULL, 
    TotalDue FLOAT NOT NULL, 
    CustomerId INT NOT NULL, 
    PRIMARY KEY(OrderId), 
    FOREIGN KEY(CustomerId) REFERENCES Customers(CustomerId) 
); 

不過即使我設置CustomerId作爲Orders表的外鍵,我仍然能夠在Orders表與CustomerId是添加行不在Customers表中。爲什麼是這樣以及如何在表格之間創建一個真正的鏈接?

這是表的樣子(從我mysql客戶端的複製/粘貼):

mysql> select * from Customers; 
+------------+-----------+----------+-------------------+------------------------+ 
| CustomerId | FirstName | LastName | Email    | Address    | 
+------------+-----------+----------+-------------------+------------------------+ 
|   1 | Jacks  | James | [email protected] | Str. Moony, No. 9  | 
|   2 | Mock  | Grad  | [email protected] | Str. Mars, No. 91  | 
|   3 | James  | Geremy | [email protected]  | Str. Monday, No. 12 | 
|   4 | Joana  | Joan  | [email protected] | Str. Comete, No. 19 | 
|   5 | Granicer | James | [email protected] | Str. Sydney, No. 651 | 
+------------+-----------+----------+-------------------+------------------------+ 
5 rows in set (0.00 sec) 

mysql> select * from Orders; 
+---------+------------+----------+----------+------------+ 
| OrderId | Date  | Quantity | TotalDue | CustomerId | 
+---------+------------+----------+----------+------------+ 
|  1 | 2014-01-09 |  10 |  340 |   3 | 
|  2 | 2014-01-09 |  1 |  50 |   3 | 
|  3 | 2014-01-09 |  11 |  55 |   5 | 
|  4 | 2014-01-09 |  11 |  55 |   51 | 
+---------+------------+----------+----------+------------+ 
4 rows in set (0.00 sec) 

正如你可以看到OrderId 4包含CustomerId 51客戶是不是在Customers表。

+0

您是否使用InnoDB引擎的表? – raj

+0

@raj我不知道,我對數據庫相當陌生...我怎麼知道? –

+0

「show table status」應該給你引擎類型 – raj

回答

0

我放棄了,使用MySQL的Web客戶端啓動...

0

您需要設置存儲引擎...更改查詢......

CREATE TABLE Orders 
(
    OrderId INT NOT NULL AUTO_INCREMENT, 
    Date DATE NOT NULL, 
    Quantity INT NOT NULL, 
    TotalDue FLOAT NOT NULL, 
    CustomerId INT NOT NULL, 
    PRIMARY KEY(OrderId), 
    FOREIGN KEY(CustomerId) REFERENCES Customers(CustomerId) 
)ENGINE=INNODB; 
+0

非常感謝你的答案!是的,那裏有一個錯誤,但我重新創建了糾正錯誤的例子,我不認爲這是事實。我仍然可以做到這一點....這裏是我的MySQL客戶端輸出:http://pastebin.com/naNP0RMq –

+0

我會編輯我的答案 – Leo

+0

謝謝! :)我馬上試試看! –

0

使用InnoDB的表引擎。

ALTER TABLE table_name ENGINE=InnoDB; 
+0

我嘗試使用'ALTER TABLE table_name ENGINE = InnoDB;'但它仍然允許我添加無效的'CustomerId' ...這是我所做的http://pastebin.com/5mXmCwHM,最後我可以添加一個客戶用id 9,當我在'客戶'表中只有5個客戶時...我做錯了什麼或者改變表格不起作用? –

+0

當您嘗試將其更改爲InnDB後插入到訂單中時,您應該會看到「無法添加或更新子行:外鍵約束失敗」。在運行alter engine查詢後,再次檢查引擎 – raj

+0

我選中並且引擎是InnoDB ... http://pastebin.com/xCPm1Q6U InnoDB是否支持外鍵? –