# 由于存在唯一索引，可以移除 Distinct

**URL:** https://meta.discourse.org/t/distinct-can-be-removed-due-to-unique-index/135225
**Category:** Development
**Created:** [2019年十二月6日 03:24 UTC](https://meta.discourse.org/t/distinct-can-be-removed-due-to-unique-index/135225 "2019-12-06T03:24:34Z")
**Posts on this page:** 1
**Showing post:** 1

<div class="post-metadata">

### Author: ![junwen\_yang](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/junwen_yang/32/163137_2.png) [@junwen\_yang](https://meta.discourse.org/u/junwen_yang)
#### Post date: [2019年十二月6日 03:24 UTC](https://meta.discourse.org/t/distinct-can-be-removed-due-to-unique-index/135225/1 "2019-12-06T03:24:34Z")

</div>

在 theme.rb 中，存在以下代码：  
[ChildTheme.where(parent\_theme\_id: theme\_id).distinct.pluck(:child\_theme\_id)](https://github.com/discourse/discourse/blob/b1207289992c752d55abbbbf7215fa37a0a5b2b2/app/models/theme.rb#L122)，其中的 distinct 可以移除，因为已在 discourse/db/migrate/20170313192741\_add\_themes.rb 中添加了唯一索引：`add_index :child_themes, [:parent_theme_id, :child_theme_id], unique: true`。

这意味着，对于两个子主题：ChildTheme1(id1, child\_theme\_id1, parent\_theme\_id) 和 ChildTheme2(id2, child\_theme\_id2, parent\_theme\_id)，如果 child\_theme\_id1 等于 child\_theme\_id2，则 id1 必然等于 id2；否则 [:parent\_theme\_id, :child\_theme\_id] 将不满足唯一性约束。因此，`ChildTheme.where(parent_theme_id: theme_id).pluck(:child_theme_id)` 返回的 child\_theme\_id 已经是唯一的，无需再调用 distinct 函数。我们可以移除它以提升性能。

---

_[View the full topic](https://meta.discourse.org/t/distinct-can-be-removed-due-to-unique-index/135225)._
