按子查询属性筛选条件查询

时间:2016-03-09 12:49:12

标签: java sql hibernate criteria

我试图实施一个有点复杂的标准 我的第一个疑问就是这个。

SELECT * FROM pin AS activepin
WHERE activepin.pin_nbr NOT IN 
( 
 SELECT p.pin_nbr 
 FROM pin AS p 
 GROUP BY p.pin_nbr,p.is_active 
 HAVING p.is_active = 0 
 AND count(*) =( 
    SELECT count(*) 
    FROM pin 
    WHERE pin_nbr = p.pin_nbr 
    GROUP BY pin_nbr)
 );

所以,为了转换到where子句(我认为有和标准不是好朋友xD)我把它转换成这个:

SELECT *
FROM pin AS activePin
WHERE activePin.pin_nbr NOT IN (
    SELECT innerQuery2.pin_nbr
    FROM(
        SELECT p.pin_nbr,
               p.is_active,
               count(*) AS quantity
        FROM pin p
        GROUP BY p.pin_nbr,
                 p.is_active) AS innerQuery2
     WHERE innerQuery2.is_active = 0
     AND innerQuery2.quantity =(
         SELECT count(*)
         FROM pin
         WHERE pin_nbr = innerQuery2.pin_nbr
         GROUP BY pin_nbr
         )
 );

然后我做了这个标准

        DetachedCriteria innerQuery3 = DetachedCriteria.forClass(Pin.class, "innerQuery3")
                .setProjection(Projections.rowCount())
                .setProjection(Projections.groupProperty("innerQuery3.pinNbr"))
                .add(Restrictions.eq("innerQuery2.pinNbr", "pinNbr"));

        DetachedCriteria innerQuery2 = DetachedCriteria.forClass(Pin.class, "innerQuery2")
                .setProjection(Projections.rowCount())
                .setProjection(Projections.groupProperty("innerQuery2.pinNbr"))
                .setProjection(Projections.groupProperty("innerQuery2.active"))
                .add(Subqueries.eq(Projections.rowCount(), innerQuery3))
                .add(Restrictions.eq("innerQuery2.pinNbr", "pinNbr"));

        DetachedCriteria innerQuery1 = DetachedCriteria.forClass(Pin.class, "innerQuery1")
                .setProjection(Projections.property("innerQuery2.pinNbr"))
                .add(Subqueries.exists(innerQuery2))
                .add(Restrictions.eq("innerQuery2.active", false));

        criteria.add(Subqueries.propertyNotIn("pinNbr", innerQuery1));

给我发出以下异常

  

org.hibernate.MappingException:未知实体:null

我认为这是因为我通过子查询值添加限制(我想在innerQuery1上我希望通过innerQuery2值进行过滤,这是因为我想在group子句之后进行过滤)。

有关如何做到这一点的任何线索?我一直在研究如何过滤子查询之外的子查询值而没有结果。

提前感谢。

1 个答案:

答案 0 :(得分:0)

SELECT p.pin_nbr 
       SUM(CASE WHEN p.is_active = 0 THEN 0 ELSE 1 END) as sum_active
       count(*) as total
FROM pin AS p 
GROUP BY p.pin_nbr
HAVING total!=sum_active

让我们先重写SQL查询。据我所知,你需要所有项目都有效的pin_nbr。

您可以使用Projections.sqlProjection()作为上述表达式。对于查询,您可以在java端添加HAVING检查或将其放在子查询中。