我有一个' field_revision ...'我试图从中获取信息的表格。使用我当前的查询,它返回与该值匹配的所有entity_id,即使revision_id小于该特定id的最高值。下面是一个示例表:
factory :request do
content { Faker::Lorem.paragraph }
association :requester
association :group
trait :has_neighbor do
association :responder
end
trait :is_fulfilled do
is_fulfilled true
end
trait :created_one_day_ago do
created_at { 1.day.ago }
end
factory :request_with_neighbor, traits: [:has_neighbor]
factory :fulfilled_request , traits: [:has_neighbor, :is_fulfilled]
factory :day_old_request, traits: [:created_one_day_ago]
end
我需要一个返回所有entity_ids的查询,其中enable_value = true且revision_id最高。对于此示例表,查询需要返回781和786,因为对于最高版本ID,这两个都是真的。
答案 0 :(得分:2)
SELECT T1.*
FROM
field_revision T1 INNER JOIN
(SELECT entity_id,MAX(revision_id) AS revision_id
FROM
field_revision
GROUP BY entity_id) T2 ON T1.entity_id = T2.entity_id AND T1.revision_id = T2.revision_id
WHERE T1.enable_value=1
编辑:OP
的说明 T1 - field_revision
的别名
T2 - 查看field_revision
entity_id
明智且最大revision_id
。
因此,在INNER JOINING中我们使用entity_id
和max(revision_id
)连接T2与T1,并在T1中打印相应的条目
希望这会有所帮助..
答案 1 :(得分:0)
如果你只想要entity_id
那么你可以试试这个(但我认为@Subin C Poonamgode的回答是正确的):
SELECT DISTINCT aa.entity_id
FROM field_revision AS aa
INNER JOIN field_revision AS bb
ON aa.entity_id = bb.entity_id
WHERE aa.revision_id > bb.revision_id AND aa.enable_value = 1;