【发布时间】:2013-10-21 19:55:57
【问题描述】:
假设我有类似的多态
| document_id | owner_type | owner_id |
| 1 | Client | 1 |
| 1 | Client | 2 |
| 2 | User | 1 |
我知道我会调用查询以查找 owner_type 和 owner_type + owner_id
SELECT * FROM document_name_ownerships WHERE owner_type = 'Client`
SELECT * FROM document_name_ownerships WHERE owner_type = 'Client` and owner_id = 1
让我们忽略如何索引document_id 我想知道在这种 SQL 场景中索引所有者列的最佳方式(性能)是什么
解决方案 1:
CREATE INDEX do_type_id_ix ON document_ownerships (owner_type, owner_id)
这样我就只有一个索引适用于两种情况
解决方案 2:
CREATE INDEX do_id_type_ix ON document_ownerships (owner_id, owner_type)
CREATE INDEX do_type_ix ON document_ownerships (owner_type)
这样,我将拥有完全匹配我将如何使用数据库的方式的索引。唯一的问题是我只有一个索引时有 2 个索引
解决方案 3:
CREATE INDEX do_id_ix ON document_ownerships (owner_id)
CREATE INDEX do_type_ix ON document_ownerships (owner_type)
单个列索引
根据我在 MySQL 控制台中使用explain 探索的内容,我得到了非常相似的结果,因为它是一个新项目,我没有足够的数据来正确探索这个,所以我可以 100% 确定(即使我填充了数百条记录的数据库)。那么有人可以根据他们的经验给我一些建议吗?
【问题讨论】:
-
谢谢你的建议,是的,我做到了,虽然你是对的,但有很多“像这样”的问题,他们并没有完全问我在问什么,我没有找到令人满意的答案我的问题中列出的解决方案中哪个是最好的