【发布时间】:2014-06-10 22:15:03
【问题描述】:
这是一个 Rails 应用程序,但我只是发布 SQL。
所以,这是我的理智测试。它可以工作,并返回相同模型的两个副本。如果我不包含where,则返回多个模型的多个副本。
SELECT \"outlets\".*
FROM \"outlets\"
INNER JOIN \"comments\"
ON \"comments\".\"commentable_id\" = \"outlets\".\"id\"
AND \"comments\".\"commentable_type\" = 'Outlet'
INNER JOIN \"statistics\"
ON \"statistics\".\"statable_id\" = \"outlets\".\"id\"
AND \"statistics\".\"statable_type\" = 'Outlet'
WHERE (\"outlets\".\"id\" = '1')
#=> [#<Outlet id: 1...>, #<Outlet id: 1...>]
# without the where I get back something like
# [...id: 1, id: 1, id: 5, id: 5, id: 5, id: 5 ]
我不知道怎么写,所以它只返回一个值(不只是使用distinct)。但这可能是我的下一个问题。
这是我正在尝试使用的 SQL。我也尝试过明确指定INNER 并颠倒等式的顺序:
SELECT \"followings\".*
FROM \"followings\"
JOIN \"outlets\"
ON \"followings\".\"followable_id\" = \"outlets\".\"id\"
AND \"followings\".\"followable_type\" = 'Outlet'
JOIN \"people\"
ON \"followings\".\"followable_id\" = \"people\".\"id\"
AND \"followings\".\"followable_type\" = 'Person'
WHERE (\"followings\".\"user_id\" = '1')
#=> []
# Exact same result from removing the WHERE clause
每个连接都有记录。如果我单独加入任一表,它们都会返回我专门为测试 SQL 而创建的结果。所以:
SELECT \"followings\".*
FROM \"followings\"
INNER JOIN \"people\"
ON \"followings\".\"followable_id\" = \"people\".\"id\"
AND \"followings\".\"followable_type\" = 'Person'
WHERE (\"followings\".\"user_id\" = '1')
#=> [<Following id: 2...>]
# And id: 1 for joining on outlets without people
这里让我难过的部分是工作版本和非工作版本本质上是相同的,但我不明白为什么它应该在一个地方工作而不是另一个地方
编辑:
进度,将followings 的JOIN 更改为LEFT OUTER JOINs 将返回所需的结果。但是为什么它同时在 outlets.id = commentable_id 和 = statable_id 工作?
而且,我刚刚尝试将outlets 也更改为 LOJ,在我见过的最长的 SQL 调用中,返回的结果列表大约是 outlets 表本身长度的两倍。所以,虽然这是一个进步,但我不认为这是一个通用的解决方案。
编辑 2:
感谢使用公认的答案进行测试,我意识到我选择的统计数据会给出“误导”的结果,因为每个出口都有一个统计数据。当我更改为更好的测试表(例如followings)时,JOIN 的行为相似。 UNION 方法返回预期的条目
【问题讨论】:
-
对于第二个查询,
followings.followable_type不能同时是= 'Outlet'和= 'Person'。您的意思是使用outlets和people进行这些比较吗? -
我想到了,但在我的工作示例中
outlets.id= commentable_id和= statable_id同时