我知道这个问题很旧,但是多年来已经引起了很多关注,我认为它缺少一个可以在类似情况下为某人提供帮助的概念。为了完整起见,我在这里添加它。
如果您不能修改原始数据库架构,那么将提供许多好的答案,并且可以很好地解决问题。
但是,如果可以修改架构,建议在customer
表中添加一个字段,该字段包含该客户id
的最新customer_data
记录:
CREATE TABLE customer (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
current_data_id INT UNSIGNED NULL DEFAULT NULL
);
CREATE TABLE customer_data (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
customer_id INT UNSIGNED NOT NULL,
title VARCHAR(10) NOT NULL,
forename VARCHAR(10) NOT NULL,
surname VARCHAR(10) NOT NULL
);
查询客户
查询尽可能简单,快捷:
SELECT c.*, d.title, d.forename, d.surname
FROM customer c
INNER JOIN customer_data d on d.id = c.current_data_id
WHERE ...;
缺点是创建或更新客户时的额外复杂性。
更新客户
每当您要更新客户时,就在customer_data
表中插入一条新记录,然后更新该customer
记录。
INSERT INTO customer_data (customer_id, title, forename, surname) VALUES(2, 'Mr', 'John', 'Smith');
UPDATE customer SET current_data_id = LAST_INSERT_ID() WHERE id = 2;
建立客户
创建客户只需插入customer
条目,然后运行相同的语句即可:
INSERT INTO customer () VALUES ();
SET @customer_id = LAST_INSERT_ID();
INSERT INTO customer_data (customer_id, title, forename, surname) VALUES(@customer_id, 'Mr', 'John', 'Smith');
UPDATE customer SET current_data_id = LAST_INSERT_ID() WHERE id = @customer_id;
包起来
创建/更新客户的额外复杂性可能令人生畏,但可以使用触发器轻松地将其自动化。
最后,如果您使用的是ORM,这确实很容易管理。ORM可以为您自动插入值,更新ID和自动将两个表连接在一起。
这是可变Customer
模型的样子:
class Customer
{
private int id;
private CustomerData currentData;
public Customer(String title, String forename, String surname)
{
this.update(title, forename, surname);
}
public void update(String title, String forename, String surname)
{
this.currentData = new CustomerData(this, title, forename, surname);
}
public String getTitle()
{
return this.currentData.getTitle();
}
public String getForename()
{
return this.currentData.getForename();
}
public String getSurname()
{
return this.currentData.getSurname();
}
}
而您的不可变CustomerData
模型仅包含吸气剂:
class CustomerData
{
private int id;
private Customer customer;
private String title;
private String forename;
private String surname;
public CustomerData(Customer customer, String title, String forename, String surname)
{
this.customer = customer;
this.title = title;
this.forename = forename;
this.surname = surname;
}
public String getTitle()
{
return this.title;
}
public String getForename()
{
return this.forename;
}
public String getSurname()
{
return this.surname;
}
}