0

我有两张表,一次旅行,一张 txns,在 oracle db 中有一对多的关系。当我触发以下查询时

Trip.where("upper(trips.domain) = 'FOOBAR.COM'  and txns.user_id = 50001 and txns.txn_type = '1'").includes([:txns]).order('trips.created_at desc').limit(10).offset(0)

为此,sql 日志中有两个查询。

    Trip Load (4920.4ms)   SELECT * FROM (
    SELECT raw_sql_.*, rownum raw_rnum_
    FROM (SELECT DISTINCT "TM"."TRIPS".id, FIRST_VALUE(trips.created_at)
 OVER (PARTITION BY "TM"."TRIPS".id ORDER BY trips.created_at desc) AS alias_0__ FROM "TM"."TRIPS" LEFT OUTER JOIN "TXNS" ON "TXNS"."TRIP_ID" = "TM"."TRIPS"."ID"
 WHERE (upper(trips.domain) = 'FOOBAR.COM' and txns.txn_type = '1') 
ORDER BY alias_0__ DESC) raw_sql_
    )
    WHERE raw_rnum_ between 1 and 10

    SQL (186.2ms)  SELECT "TM"."TRIPS"."ID" AS t0_r0, "TM"."TRIPS"."TRIP_REF" AS t0_r1, "TM"."TRIPS"."TRIP_NAME" AS t0_r2, 
"TM"."TRIPS"."START_DATE_TIME" AS t0_r3, "TM"."TRIPS"."END_DATE_TIME" AS t0_r4, "TM"."TRIPS"."AMOUNT" AS t0_r5, "TM"."TRIPS"."CREATED_AT" AS t0_r6,
 "TM"."TRIPS"."UPDATED_AT" AS t0_r7, "TM"."TRIPS"."USER_ID" AS t0_r8, 
"TM"."TRIPS"."BOOKING_STATUS" AS t0_r9, "TM"."TRIPS"."TRAVELLERS" AS t0_r10, 
"TM"."TRIPS"."USER_TRIP_NAME" AS t0_r11, "TM"."TRIPS"."CONTACT_DETAIL_ID" AS t0_r12, 
"TM"."TRIPS"."AIR" AS t0_r13, "TM"."TRIPS"."HOTEL" AS t0_r14, "TM"."TRIPS"."DOMAIN" AS t0_r15, "TM"."TRIPS"."TRAIN" AS t0_r16, "TM"."TRIPS"."TAGS" AS t0_r17, "TM"."TRIPS"."CURRENCY" AS t0_r18, "TM"."TRIPS"."CUR_INR_VALUE" AS t0_r19, 
"TM"."TRIPS"."COMPANY_ID" AS t0_r20, "TXNS"."ID" AS t1_r0, "TXNS"."TRIP_ID" AS t1_r1,
 "TXNS"."USER_ID" AS t1_r2, "TXNS"."TXN_TYPE" AS t1_r3, "TXNS"."STATUS" AS t1_r4, "TXNS"."SOURCE_TYPE" AS t1_r5, "TXNS"."SOURCE_ID" AS t1_r6, "TXNS"."EXTERNAL_REFS" AS t1_r7, "TXNS"."CREATED_AT" AS t1_r8, "TXNS"."IP_NUMBER" AS t1_r9, "TXNS"."MISC" AS t1_r10 FROM "TM"."TRIPS" LEFT OUTER JOIN "TXNS" ON "TXNS"."TRIP_ID" = "TM"."TRIPS"."ID" WHERE "TM"."TRIPS"."ID" IN (11620660, 11620651, 11620649, 11620647, 11620646, 11620645, 11620644, 11620642, 11620641, 11620636) AND (upper(trips.domain) = 'FOOBAR.COM' and txns.txn_type = '1') ORDER BY trips.created_at desc

我想知道为什么活动记录会触发两个查询

4

2 回答 2

1

您有两个查询的原因是您正在使用基于连接的包含(因为您的 where 子句引用了txns关联中的列)并且因为您有一个限制。

因为您要加入一个有很多导轨,所以不能只在您的查询上加上限制 10 - 举一个极端的例子,如果您有 1 次行程和 10 个关联的 txns,那么将限制 10 添加到查询导轨通常会运行可能只会返回那个1 个行程(与 10 个匹配的 txns 中的每一个连接)而不是 10 个不同的行程

为了解决这个问题,rails 首先查找与您的条件匹配的前 10 个 Trip 行,然后触发第二个查询以加载那些包含您想要包含的关联的 trip 行。

于 2012-11-06T14:28:37.593 回答
0

答案可以在这个 SO question and answerinclude中看到 Rails与 Rails之间的区别joins

于 2012-11-06T14:18:07.493 回答