我正在创建一个表,这让我感到疑惑。
如果我存储,比方说有make的汽车(fx BMW,Audi等),如果我将make存储为int或varchar,会对查询速度有什么影响吗?
也是如此
SELECT * FROM table WHERE make = 5 AND ...;比…快/慢
SELECT * FROM table WHERE make = 'audi' AND ...;或者速度会大致相同吗?
发布于 2010-02-27 18:19:55
Int比较比varchar比较快,这是因为Int比varchars占用的空间少得多。
这对于非索引访问和索引访问都是正确的。最快的方法是使用带索引的int列。
正如我所看到的,您已经标记了问题postgreql,您可能会对不同日期类型的空间使用情况感兴趣:
int字段占用4 bytes plus the actual strings.,4通常足够多( -2147483648到+2147483647 )
发布于 2016-09-23 07:10:58
一些粗略的基准:
Postgres 9.x中有400万条记录
Table A = base table with some columns
Table B = Table A + extra column id of type bigint with random numbers
Table C = Table A + extra column id of type text with random 16-char ASCII strings在8 8GB内存、i7、固态硬盘笔记本电脑上的结果:
Size on disk: A=261MB B=292MB C=322MB
Non-indexed by id: select count(*), select by id: 450ms same on all tables
Insert* one row per TX: B=9ms/record C=9ms/record
Bulk insert* in single TX: B=140usec/record C=180usec/record
Indexed by id, select by id: B=about 200us C=about 200us
* inserts to the table already containing 4M records因此,对于这个设置,只要您的索引适合RAM,bigint和16个字符的text在速度上没有差别。
发布于 2010-02-27 18:26:12
使用int而不是varchar会更快一些。对于速度来说,更重要的是在字段上建立索引,以便查询可以用来查找记录。
使用int还有另一个原因,那就是规范化数据库。与其在表格中存储成千上万次的文本'Mercedes-Benz‘,不如存储它的id,并在一个单独的表格中存储一次品牌名称。
https://stackoverflow.com/questions/2346920
复制相似问题