我尝试按以下SQL查询中的左外连接上的字段对检索到的记录进行排序:
@companies = Company.scoped
@companies = @companies.where("companies.is_deleted = 'f' AND companies.state IN (?)", ["draft", "pending"])
@companies = @companies.includes(:events)
@companies = @companies.order("events.created_at DESC")
SELECT "companies"."id" AS t0_r0, "companies"."name" AS t0_r1, "companies"."reference" AS t0_r2, "companies"."state" AS t0_r3, "companies"."description" AS t0_r4, "companies"."remarks" AS t0_r5 "events"."id" AS t2_r0, "events"."eventable_type" AS t2_r1, "events"."eventable_id" AS t2_r2, "events"."event_type" AS t2_r3, "events"."creator_company_id" AS t2_r4, "events"."creator_user_id" AS t2_r5, "events"."created_at" AS t2_r6
FROM "companies"
LEFT OUTER JOIN "events" ON "events"."eventable_id" = "companies"."id" AND "events"."eventable_type" = 'company'
WHERE "companies"."is_deleted" = 'f' AND companies.state IN ('draft','pending')
ORDER BY events.created_at DESC
但检索到的记录未按预期正确排序(即通过events.created_at)
如何在保持绩效的同时成功实现这一目标的任何线索?
答案 0 :(得分:1)
我认为您不应该使用LEFT JOIN,或者如果代码在这种情况下生成LEFT JOIN,则可能是错误的。
表A和B的左外连接(或简称左连接)的结果始终包含“左”表(A)的所有记录,“ - http://en.wikipedia.org/wiki/Join_%28SQL%29#Left_outer_join
因此,如果您不想拥有公司的所有记录,即使事件没有匹配,您也不应该在这里使用左连接。它将为右侧表生成具有NULL值的行。