1

想象以下问题:有人想买一篮子水果,里面有来自非洲和南美洲的绿色水果,但没有来自非洲的红色水果。

为此,我们考虑以下课程:



    class Basket
    {
      int id;
      Collection<Fruit> fruits; 
    }

    class Fruit
    {
      int id;
      int basketId;
      String origin
      Color color;
    }

映射将是 MxM。Fruit 没有 Basket 对象,但如有必要,我可以实现它。

对于本机 SQL,我将使用:



    SELECT * 
    FROM 
      Basket b 
    JOIN 
    (
      SELECT DISTINCT basketId 
      FROM Fruit 
      WHERE color='green' AND (origin='Africa' OR origin='South America')
    ) f1 ON (b.id=f1.basketId) 
    LEFT JOIN 
    (
      SELECT DISTINCT basketId 
      FROM Fruit 
      WHERE color='red' AND (origin='Africa')
    ) f2 ON (b.id=f2.basketId) 
    WHERE f2.basketId IS NULL 

JPQL 中的查询是什么?

我已经尝试过:



    SELECT b 
    FROM Basket b 
    WHERE 
      b.id IN (
        SELECT f1.basketId FROM Fruit f1 
        WHERE f1.color='green' AND (f1.origin='Africa' OR f1.origin='South America')
      ) AND
      b.id NOT IN (
        SELECT f2.basketId FROM Fruit f2 
        WHERE f2.color='red' AND (origin='Africa'))

但是这个查询花费了 12000 毫秒而不是 50 毫秒。(这只是一个简单的例子。真正的表有大约 750000 个“水果”和 10000 个“篮子”,每个都有更多的字段。)

提前致谢

杰拉德

4

2 回答 2

0

You could try

select b from Basket b where
    exists (select f.id from Fruit f where f.basket = b and f.color = 'green')
    and not exists (select f.id from Fruit f where f.basket = b and f.color = 'red')

But I'm not sure it would be faster. It depends on the execution plan, which depends on the database indexes. There should be an index on Fruit.basketId and on Fruit.color.

于 2011-09-15T16:28:19.360 回答
0

这行得通吗?

select b from Basket b join b.fruits f where f.color = 'green' and not f.color = 'red';

连接可能是可选的,所以它也可能是

select b from Basket b where b.fruits.color = 'green' and not b.fruits.color = 'red';
于 2011-09-15T17:27:46.050 回答