sql其中x = y和x = z以及

时间:2019-05-11 20:32:14

标签: sql spring spring-mvc hql

@英语不是我的母语。

我有一个代码(正在运行):

@Query("select new java.entity.dto.ProductsDTO(" +
        "p," +
        "count(c)," +
        "sum(case when c.user = :user then 1 else 0 end) > 0," +
        "sum(case when cart.user = :user then 1 else 0 end) > 0," +
        "sum(case when wish.user = :user then 1 else 0 end) > 0) " +
        "from Products p " +
        "left join p.commentaries c " +
        "left join p.carts cart " +
        "left join p.wishLists wish " +
        "left join p.tags tags " +
        "where p.categories = :categories " +
        "and tags.id in :tags " +
        "group by p,:user")
Page<ProductsDTO> findAllByCategoriesAndTags(Pageable pageable, @Param("categories") Categories categories, @Param("user") User user, @Param("tags") List<Long> tags);

当我阅读此部分时,“ tags.id =:tags”的工作方式如下: “ id =标签1或id =标签2或id =标签3 ...”。

所以,我该怎么写这样的东西:“ id1 = tag1或id1 = tag2和id2 = tag1或id2 = tag2”

1 个答案:

答案 0 :(得分:0)

  

当我阅读此部分时,“ tags.id =:tags”的工作方式类似于:“ id = tag1或id = tag2或id = tag3 ...”。

     

所以,我怎么写这样的东西:“ id1 = tag1或id1 = tag2 id2 = tag1或id2 = tag2

只需在已经存在的语句之后追加另一个AND语句:

    AND tags.id1 in :tags 
    AND tags.id2 in :tags

我假设您的意思是“ (id1 = tag1 or id1 = tag2) and (id2 = tag1 or id2 = tag2)”。不过,请注意, AND 逻辑运算优先于 OR 运算。如果没有括号,您的表达式将被解析为“ id1 = tag1 or (id1 = tag2 _and_ id2 = tag1) or id2 = tag2”…