优化嵌套的SELECT查询并使用ActiveRecord查询API执行此操作

时间:2013-06-01 17:08:45

标签: sql ruby-on-rails activerecord rails-activerecord

我有这个SQL查询来选择我的一些优惠,它按预期工作。

SELECT * FROM `offers` WHERE region='26'

AND EXISTS (
SELECT * FROM `modificator_values` WHERE
    `modificator_values`.`offer_id`=`offers`.`id` AND
     (modificator_values.modificator_id = "5") AND (modificator_values.data = "data1")
) 

AND EXISTS (
SELECT * FROM `modificator_values` WHERE
     `modificator_values`.`offer_id`=`offers`.`id` AND
     (modificator_values.modificator_id = "8") AND (modificator_values.data = "data2")
)

有没有办法优化它并使用ActiveRecord查询API来实现?

1 个答案:

答案 0 :(得分:0)

虽然没有使用任何API,但我建议你使用这个技巧,你只检查两个子查询中是否存在,并且可以通过这样做来节省“双倍”时间:

SELECT * FROM offers 
WHERE region='26'

AND (SELECT COUNT(*)
  FROM (
    SELECT modificator_id,COUNT(data) 
    FROM modificator_values 
    WHERE
      modificator_values.offer_id=1 AND
       (((modificator_values.modificator_id = "5") AND (modificator_values.data = "data1")) OR
       ((modificator_values.modificator_id = "8") AND (modificator_values.data = "data2")))
    GROUP BY modificator_id 
    ) s
    ) > 1

我已在此架构上测试过它:

CREATE TABLE offers 
    (
     id int auto_increment primary key, 
     region varchar(20)
    );
CREATE TABLE modificator_values 
    (
     modificator_id int auto_increment primary key, 
     data varchar(20), 
     offer_id int
    );

INSERT INTO offers VALUES (1,'26');
INSERT INTO modificator_values VALUES(5,'data1',1);
INSERT INTO modificator_values VALUES(8,'data2',1);