我有一个与颜色表有关系的产品表
一个产品可以有多种颜色...exp: 产品 A: 有红色、绿色、蓝色、黄色。
Product
-----------
ProductID
Name
Color
-----------
ProjectID
Color
我希望找到至少包含红色和绿色的产品
对于动态大小,我还希望添加 name = "doggy"
SQL语句是
select * from product pd where pd.ProductID = (select cr.productID from color cr where cr.color="RED" or cr.color="GREEN" group by cr.productID having rowcount=2)
and name like '%doggy'
如何在没有依赖子查询的情况下创建条件。
问题链接至
1) Criteria, Subqueries, Group By and Having more
2) One to Many search using AND condition
正如您所见,这个问题没有好的解决方案。
最佳答案
DetachedCriteria colorCrit = DetachedCriteria.For(Product.class)
.createAlias("colors","color")
.add(Restriction.eq("color.color", "RED")
.add(Restriction.eq("color.color", "GREEN")
.SetProjection(new GroupByHavingProjection("id", Projections.count("id"), "=", 2));
Criteria criteria = createCriteria()
.add(Subqueries.in("id", colorCrit)
.list();
使用 here 中的 groupbyhaving 实现看起来像:
// (c) 2008-2010 FURTHeR Project, Health Sciences IT, University of Utah<br>
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.criterion.CriteriaQuery;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.PropertyProjection;
public class GroupByHavingProjection extends PropertyProjection
{
private static final long serialVersionUID = -3316795021430206470L;
private final Projection havingProjection;
private final String groupByProperty;
private String op;
private Object value;
public GroupByHavingProjection(final String groupByProperty, final Projection projection, final String op, final Object value)
{
super(groupByProperty, true);
this.projection = projection;
this.groupByProperty = groupByProperty;
this.op = op;
this.value = value;
}
}
关于java - 标准、独立子查询、分组依据和拥有更多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11456286/