0

我有这个 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 来实现?

4

1 回答 1

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);
于 2013-06-01T17:39:09.390 回答