如果我理解MySQL表的工作原理,那么表的每个实例都会占用其完整的内存分配,即使大多数列都是空白的。例如,即使为空,空白TEXT列也将消耗65536个字节。如果稍后只有几个字符输入此列,它仍将消耗完整的65536个字节。
在Rails迁移中,您可以为每列设置字符限制。例如,您可以将TEXT列限制为500个字符。在执行此操作时,您是否还减少了该列的分配内存,因此它会消耗大量字节而不是65536字节,以表示500个字符?
如果我确信该列将始终限制为500个字符,那么将其限制在数据库中还是仅限于模型验证中是否常见?
答案 0 :(得分:4)
例如,空白TEXT列即使为null也会消耗65536个字节。如果稍后只有几个字符输入此列,它仍将消耗完整的65536个字节。
不正确的。见Data Type Storage Requirements:
字符串类型的存储要求
在下表中,
M
表示非二进制字符串类型的字符长度和二进制字符串类型的字节。L
表示给定字符串值的实际字节长度。+-----------------------------+-------------------------------------------------+ | Data Type | Storage Required | +-----------------------------+-------------------------------------------------+ | CHAR(M) | M × w bytes, 0 <= M <= 255, where w is the | | | number of bytes required for the maximum-length | | | character in the character set | +-----------------------------+-------------------------------------------------+ | BINARY(M) | M bytes, 0 <= M <= 255 | +-----------------------------+-------------------------------------------------+ | VARCHAR(M), VARBINARY(M) | L + 1 bytes if column values require 0 – 255 | | | bytes, L + 2 bytes if values may require more | | | than 255 bytes | +-----------------------------+-------------------------------------------------+ | TINYBLOB, TINYTEXT | L + 1 bytes, where L < 28 | +-----------------------------+-------------------------------------------------+ | BLOB, TEXT | L + 2 bytes, where L < 216 | +-----------------------------+-------------------------------------------------+ | MEDIUMBLOB, MEDIUMTEXT | L + 3 bytes, where L < 224 | +-----------------------------+-------------------------------------------------+ | LONGBLOB, LONGTEXT | L + 4 bytes, where L < 232 | +-----------------------------+-------------------------------------------------+ | ENUM('value1','value2',...) | 1 or 2 bytes, depending on the number of | | | enumeration values (65,535 values maximum) | +-----------------------------+-------------------------------------------------+ | SET('value1','value2',...) | 1, 2, 3, 4, or 8 bytes, depending on the number | | | of set members (64 members maximum) | +-----------------------------+-------------------------------------------------+