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).
你必须问自己这是一对一的关系还是一对一的关系。也就是说,是否每个帐户都有一个客户,每个客户都有一个帐户。或者会有没有账户的客户。你的问题暗示后者。
如果你想有一个严格的 1 对 1 关系,只需合并两个表。
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 并想要帐户信息,则加入 customersaccounts 和帐户:
SELECT a.*
FROM customersaccounts ca
INNER JOIN accounts a ca.account_id=a.account_id
AND ca.customer_id=mycustomerid;
由于索引,这将非常快。
您还可以创建一个 VIEW,它为您提供合并的 customersaccounts 表的效果,同时保持它们分开
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;