打印引用表的列值

时间:2014-03-22 11:44:14

标签: sql foreign-keys

为了避免冗余,为了节省空间,出于数据库强度的原因并轻松添加新的可能值,我设计了这个数据库布局:

CREATE TABLE IF NOT EXISTS `tmcc_make` (
  `id` tinyint UNSIGNED NOT NULL AUTO_INCREMENT,
  `make` varchar(60) NOT NULL UNIQUE,
  `status` bit DEFAULT NULL COMMENT 'NULL = active | 1 = deprecated',
  PRIMARY KEY (`id`)
);

CREATE TABLE IF NOT EXISTS `tmcc_model` (
  `id` smallint UNSIGNED NOT NULL AUTO_INCREMENT,
  `model` varchar(60) NOT NULL UNIQUE,
  `make` tinyint UNSIGNED NOT NULL,
  `status` bit DEFAULT NULL COMMENT 'NULL = active | 1 = deprecated',
  PRIMARY KEY (`id`),
  FOREIGN KEY (`make`) REFERENCES tmcc_make(`id`)
);

CREATE TABLE IF NOT EXISTS `tmcc_vehicle` (
  `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `make` tinyint UNSIGNED NOT NULL,
  `model` smallint UNSIGNED NOT NULL,
  [...] 
  PRIMARY KEY (`id`),
  FOREIGN KEY (`make`) REFERENCES tmcc_make(`id`),
  FOREIGN KEY (`model`) REFERENCES tmcc_model(`id`)
);

现在,我知道将描述字段用作前两个表的PK会更容易,这样我就已经准备好了这些值,但这会占用更多的空间。检索匹配id的字符串的最佳和不太复杂的方法是什么?你认为使用更多空间并直接设置字符串而不是整数pk会更好吗?

1 个答案:

答案 0 :(得分:1)

我建议您对数据结构进行一些更改。首先,对于不同表中具有相同名称的列(例如modelmake),不要使用不同的类型。此外,我更喜欢让主键标识实体,因此名称与外键匹配。最后,你应该在make表中有vehicle(除非你故意这样做)。该结构是车辆 - >模型 - >使。我建议这个结构:

CREATE TABLE IF NOT EXISTS `tmcc_make` (
  `makeid` tinyint UNSIGNED NOT NULL AUTO_INCREMENT,
  `make` varchar(60) NOT NULL UNIQUE,
  `status` bit DEFAULT NULL COMMENT 'NULL = active | 1 = deprecated',
  PRIMARY KEY (`id`)
);

CREATE TABLE IF NOT EXISTS `tmcc_model` (
  `modelid` smallint UNSIGNED NOT NULL AUTO_INCREMENT,
  `model` varchar(60) NOT NULL UNIQUE,
  `makeid` tinyint UNSIGNED NOT NULL,
  `status` bit DEFAULT NULL COMMENT 'NULL = active | 1 = deprecated',
  PRIMARY KEY (`id`),
  FOREIGN KEY (`makeid`) REFERENCES tmcc_make(`makeid`)
);

CREATE TABLE IF NOT EXISTS `tmcc_vehicle` (
  `vehicleid` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `modelid` smallint UNSIGNED NOT NULL,
  [...] 
  PRIMARY KEY (`vehicleid`),
  FOREIGN KEY (`model`) REFERENCES tmcc_model(`modelid`)
);

然后获取结果的查询是:

select v.id, mo.model, ma.make
from vehicle v join
     tmcc_model mo
     on v.modelid = mo.modelid join
     tmcc_make ma
     on mo.makeid = ma.makeid;

您可能还希望将status存储在单独的表中,特别是如果要在两个表中使用相同的值。

相关问题