我是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
表。
您是否使用InnoDB引擎的表? – raj
@raj我不知道,我對數據庫相當陌生...我怎麼知道? –
「show table status」應該給你引擎類型 – raj