【问题标题】:Mysql unique constraint > 16 columnsMysql唯一约束> 16列
【发布时间】:2016-05-16 23:02:51
【问题描述】:

我想尽可能多地使用标准化。但是,我无法理解这个。

假设我有这样的财务数据:

账本# |维度1 |维度2 |维度3

4000 | 100 | 200 | 300

5113 | 100 | 298 | 300

我需要确保这 4 列的每个组合都是唯一的。我知道唯一约束,所以我在所有提到的列上都加上了一个“唯一”。

但是...如果维度列的数量必须是 25 个,那么维度列将是 25 个而不是前面提到的 3 个呢?我将如何使用唯一约束?我知道一个约束只能容纳 16 列或 3072 个字节,仅此而已。

我正在考虑使用某种哈希,但还没有完全弄清楚如何做到这一点。

任何人都可以通过提供想法/信息/示例来帮助我吗?

如果有一个完全不同的想法可以在没有唯一约束的情况下实现这一点,我完全愿意听到它!

【问题讨论】:

  • 如果你完全生气了,你可以尝试用不同的限制重新编译 MySQL,或者使用不同的 RDBMS,比如 Postgres。一种宽松的方法是使用 SHA1 将单个键中的所有值组合起来,如果这是可接受的结果,则将其用作唯一性约束。
  • 使用散列作为唯一约束可以解决问题(使用触发器填充值)但是在实践中这种情况发生的频率如何?
  • 只是一个愚蠢的猜测,但看起来 ledger# 是我唯一需要唯一的东西。
  • dimension1...dimensionN 的取值范围是多少?
  • @tadman:使用 sha1 哈希作为唯一约束看起来最有希望。我通常使用“ON DUPLICATE KEY UPDATE ID=LAST_INSERT_ID(ID)”来获取插入行的 ID 或现有行的 ID。问题是虽然哈希需要是唯一的列,但我不能将 ID 作为主键,因为 MySql 抱怨它......关于如何解决这个问题的任何想法?所以我需要哈希是唯一的并且能够检索现有行的ID......如果它已经存在......

标签: mysql constraints unique


【解决方案1】:

选项1:

CREATE TABLE bigboy (
  ledger_sub1 int unsigned not null COMMENT 'foreign key me...',
  ledger_sub2 int unsigned not null COMMENT 'forgein key me...'
  PRIMARY KEY (ledger_sub1,ledger_sub2)
)

CREATE TABLE bigboy_sub1 {
 ledger int unsigned auto_increment,
 dim01 int unsigned not null,
 ...
 dim15 int unsigned not null,
 PRIMARY KEY (ledger),
 UNIQUE KEY uk1 (dim01..dim15)
)

CREATE TABLE bigboy_sub2 {
 ledger int unsigned auto_increment,
 dim16 int unsigned not null,
 ...
 dim30 int unsigned not null,
 PRIMARY KEY (ledger),
 UNIQUE KEY uk1 (dim16..dim30)
)

ledger_sub1 = INSERT IGNORE INTO bigboy_sub1(dim01..dim15) and return ledger;
ledger_sub2 = INSERT IGNORE INTO bigboy_sub2(dim16..dim30) and return ledger;
its_unique = INSERT IGNORE INTO bigboy(ledger_sub1,ledger_sub2);

选项2:

CREATE TABLE bigboy {
 ledger int unsigned auto_increment,
 dim01 int unsigned not null,
 ...
 dim30 int unsigned not null,
 bigboy_uniq VARCHAR(301) not null,
 PRIMARY KEY (ledger),
 UNIQUE KEY uk1 (bigboy_uniq)
);
where bigboy_uniq = concatenation of LPAD'ed dim01..dim30

选项3:

CREATE TABLE bigboy {
 ledger int unsigned auto_increment,
 dim01 int unsigned not null,
 ...
 dim30 int unsigned not null,
 fingers_crossed VARCHAR(32) not null,
 PRIMARY KEY (ledger),
 UNIQUE KEY uk1 (fingers_crossed)
);
where fingers_crossed = md5 of LPAD'ed dim01..dim30 string

(免责声明 - 我不会单独使用任何这些,除非乱搞)

【讨论】:

  • 解释清楚,谢谢!我会试试看:-)
猜你喜欢
  • 1970-01-01
  • 2010-11-16
  • 2017-01-10
  • 1970-01-01
  • 2019-02-27
  • 2012-01-20
  • 2010-12-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多