CREATE TABLE accounts(
account_id INT NOT NULL AUTO_INCREMENT,
customer_id INT( 4 ) NOT NULL ,
account_type ENUM( 'savings', 'credit' ) NOT NULL,
balance FLOAT( 9 ) NOT NULL,
PRIMARY KEY ( account_id )
)
and
CREATE TABLE customers(
customer_id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
address VARCHAR(20) NOT NULL,
city VARCHAR(20) NOT NULL,
state VARCHAR(20) NOT NULL,
)
How do I create a 'relationship' between the two tables? I want each account to be 'assigned' one customer_id (to indicate who owns it).
您必须问自己这是一对一的关系还是很多关系中的一种。也就是说,每个帐户是否都有一个客户,每个客户都有一个帐户。否则会有没有帐户的客户。您的问题暗示了后者。
如果要建立严格的一对一关系,只需合并两个表即可。
CREATE TABLE customers(
customer_id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
address VARCHAR(20) NOT NULL,
city VARCHAR(20) NOT NULL,
state VARCHAR(20) NOT NULL,
account_type ENUM( 'savings', 'credit' ) NOT NULL,
balance FLOAT( 9 ) NOT NULL,
)
在另一种情况下,在两个表之间创建关系的正确方法是创建一个关系表。
CREATE TABLE customersaccounts(
customer_id INT NOT NULL,
account_id INT NOT NULL,
PRIMARY KEY (customer_id, account_id)
FOREIGN KEY customer_id references customers (customer_id) on delete cascade,
FOREIGN KEY account_id references accounts (account_id) on delete cascade
}
然后,如果您有一个customer_id并想要帐户信息,则可以加入customers帐户和帐户:
SELECT a.*
FROM customersaccounts ca
INNER JOIN accounts a ca.account_id=a.account_id
AND ca.customer_id=mycustomerid;
由于索引,这将是令人眼花quick乱的。
您还可以创建一个VIEW,该视图可为您提供合并后的客户帐户表的效果,同时将它们分开
CREATE VIEW customeraccounts AS
SELECT a.*, c.* FROM customersaccounts ca
INNER JOIN accounts a ON ca.account_id=a.account_id
INNER JOIN customers c ON ca.customer_id=c.customer_id;