我有一个与颜色表有关系的产品表
一个产品可以有多种颜色... 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);
不起作用,因为行数不是属性 = 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
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
以上假设您不能拥有具有两种红色的产品,即元组 (color, product_id)
在表 color
中有唯一约束.
关于java - 条件、子查询、分组依据和更多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11426562/