条件、子查询、分组依据和拥有更多



我有一个与颜色表有关系的产品表

一个产品可以有多种颜色。。。exp:产品A:有红色、绿色、蓝色、黄色。

我希望找到至少含有红色和绿色的产品。

     DetachedCriteria colorCrit = DetachedCriteria.forClass(Color.class);
        ProjectionList colorList = new Projections.projectionList();
        colorList.add(Projections.groupProperty("productID"));
        colorList.add(Projections.rowCount(),"abc");
        colorCrit.setProjection(colorList);
        colorCrit.add(Restrictions.eq("color", "GREEN")
    colorCrit.add(Restrictions.eq("color", "RED")
    colorCrit.add(Restrictions.eq("abc",2);
    Criteria productCrit = new Criteria(Product.class);
    productCrit.add(Suqueries.in("id",colorCrit));
list<Product> productList = productCrit.list();

我使用了上面的代码,但我无法通过Projections.rowCount()来实现组。

我已经尝试过.as,但它会导致一个额外的列,使分离的条件不适合Suqueries。(oracle异常值太多)

colorCrit.add(Restrictions.eq(Projections.rowCount(),2);>不起作用,因为rowcount不是属性=x

select * from product pd where pd.id = (select cr.productID from color cr where cr.color="RED" or cr.color="GREEN" group by  cr.productID having rowcount=2

以上应该是正确的SQL查询。

我可以知道有解决方案吗?

我将使用以下查询:

select p from Product p where 
2 = (select count(color.id) from Product p2 
     inner join p2.colors color
     where p2.id = p.id
     and color.color in ('GREEN', 'RED'))

以上内容可在的标准中进行翻译

Criteria c = session.createCriteria(Product.class, "p")
DetachedCriteria sub = DetachedCriteria.forClass(Product.class, "p2");
sub.createAlias("p2.colors", "color");
sub.add(Restrictions.eqProperty("p2.id", "p.id"))
sub.add(Restrictions.in("color.color", new String[] {"RED", "GREEN"}));
sub.setProjection(Projections.count("color.id"));
c.add(Subqueries.eq(2, sub)); // or 2L

以上假设您不可能有两种颜色为RED的乘积,即元组(color, product_id)在表color中具有唯一约束。

相关内容

最新更新