让我们假设三个模型,标准连接:class Mailbox < ActiveRecord::Base has_many :addresses has_many :domains, :through => :addressesendclass Address < ActiveRecord::Base belongs_to :mailbox belongs_to :domainendclass Domain < ActiveRecord::Base has_many :addresses has_many :mailboxes, :through => :addressesend现在很明显,如果您想知道任何给定的邮箱在哪些域中有地址,您有两种可能的方法:m = Mailbox.first# either: SELECT DISTINCT domains.id, domains.name FROM "domains" INNER JOIN# "addresses" ON "domains".id = "addresses".domain_id WHERE# (("addresses".mailbox_id = 1))m.domains.all(:select => 'DISTINCT domains.id, domains.name')# or: SELECT domains.id, domains.name FROM "domains" INNER JOIN "addresses" ON# "domains".id = "addresses".domain_id WHERE (("addresses".mailbox_id = 1))# GROUP BY domains.id, domains.namem.domains.all(:select => 'domains.id, domains.name', :group => 'domains.id, domains.name')我的问题是我不知道哪种解决方案更好。当我不指定任何其他条件时,PostgreSQL 查询规划器偏向于解决方案二(按预期工作),但如果我向查询添加条件,则归结为“唯一”与“组”:与“不同”: Unique (cost=16.56..16.57 rows=1 width=150) -> Sort (cost=16.56..16.56 rows=1 width=150) Sort Key: domains.name, domains.id -> Nested Loop (cost=0.00..16.55 rows=1 width=150) -> Index Scan using index_addresses_on_mailbox_id on addresses (cost=0.00..8.27 rows=1 width=4) Index Cond: (mailbox_id = 1) -> Index Scan using domains_pkey on domains (cost=0.00..8.27 rows=1 width=150) Index Cond: (domains.id = addresses.domain_id) Filter: (domains.active AND domains.selfmgmt)(9 rows)使用“GROUP BY”:Group (cost=16.56..16.57 rows=1 width=150) -> Sort (cost=16.56..16.56 rows=1 width=150) Sort Key: domains.name, domains.id -> Nested Loop (cost=0.00..16.55 rows=1 width=150) -> Index Scan using index_addresses_on_mailbox_id on addresses (cost=0.00..8.27 rows=1 width=4) Index Cond: (mailbox_id = 1) -> Index Scan using domains_pkey on domains (cost=0.00..8.27 rows=1 width=150) Index Cond: (domains.id = addresses.domain_id) Filter: (domains.active AND domains.selfmgmt)(9 rows)我真的不确定如何确定检索这些数据的更好方法。我的直觉告诉我选择“GROUP BY”,但我找不到任何足够具体的文档来解决这个问题。我应该使用 ":group"还是 ":select => 'DISTINCT'"?该选择是否与其他现代 RDBMS 相同,例如Oracle、DB2 或 MySQL(我无权访问它们,因此无法执行测试)? 最佳答案 如果您使用的是 Postgresql GROUP BY 而不是 DISTINCT 因为它的计划更有效。在 8.4 中没有区别,因为 DISTINCT 被“教”为也能够使用组运算符。关于sql - 更好的 SQL - :group vs. :select => 'DISTINCT',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1385572/
10-13 04:46