问题
Is it OK if I create a composite primary key from 4 columns? Like:
PRIMARY KEY(name, slug, type, parent)
So there should not be more than one row with the same name, slug, type and parent. Are there too many columns? Will it affect performance?
I'm using sqlite btw.
回答1:
It's usually recommended to have an ID field that is unique on its own. Comparing INTEGER values is faster than comparing strings, so your composite key will affect performance negatively.
Adding a column with the following as the datatype would be ideal if you will be joining to other tables:
INTEGER PRIMARY KEY AUTOINCREMENT
回答2:
SQLite has a limit of 2000 columns in an index.
The performance of a 4-column index will not be much different from that of a 3-column index.
However, generic performance statement are not interesting. What matters for you is whether this table structure is performant enough for you, which you can find out only by measuring it.
Please note that if you do lookups on only one column, that column must be the first one in an index to allow the index to be used.
来源:https://stackoverflow.com/questions/16966765/composite-primary-key-limit