我目前正在开发一些项目,将大量数据插入到某些表中。为了确保我的系统足够快,我想将我的巨大表格分成一些代表月份数据的小表。我知道它将如何工作,但我还需要更多的信息。
我的表的主键必须是连续的,所以我想到了一个看起来像这样的架构:
CREATE TABLE `foo` (
`id` bigint(11) unsigned NOT NULL AUTO_INCREMENT,
}
CREATE TABLE `foo012014` (
`id` bigint(11),
`description` varchar(255),
}
CREATE TABLE `foo022014` (
`id` bigint(11),
`description` varchar(255),
}
在每次插入时,PHP页面将查看该月份是否已存在表格,否则将创建该表格。
问题是,如何将“foo”子表主键绑定到“foo”主表?另外,这种设计是不好的做法还是好的?
答案 0 :(得分:1)
这不是一个好的实践,也很难你的疑问。
只有id,你已经有了一个索引,可以更好地索引你的数据。
如果您的查询编写得很好,那么在数据库中执行查询的时间相对较少,只有100万行或20行。
为了更好的维护,我建议如下:
food
中添加一个新字段:created datetime DEFAULT CURRENT_TIMESTAMP
(适用于MySQL 5.6 +,适用于其他版本,或在每个插入中手动设置,或更改为timestamp
)并且,只需使用此字段将您的数据库分组为日期时间值,例如:2014-01-24 13:18
。
选择和操作很容易。
使用month
和year
创建一个外部表格,如下所示:
drop table if exists foo_periods;
create table foo_periods (
id int not null auto_increment primary key,
month smallint(4) not null,
year smallint(4) not null,
created datetime,
modified datetime,
active boolean not null default 1,
index foo_periods_month (month),
index foo_periods_year (year)
);
如果感觉更好,可以将月份中的smallint
更改为varchar
。
然后,只需创建一个FK
,然后完成!
ALTER TABLE foo
ADD COLUMN foo_period_id int not null;
ALTER TABLE foo
ADD CONSTRAINT foo_foo_period_id
FOREIGN KEY (foo_period_id)
REFERENCES foo_periods (id);
如果您想了解更多有关MySQL中的碎片/优化的信息,请this is a great post。