简体   繁体   English

如何在MySQL查询中使用规范使两个“ OR”条件与多个“ AND”条件

[英]How to use specification to make two “OR” condition with multiple “AND” condition in mysql query

I want to make a following query with help of Specification 我想在规范的帮助下进行以下查询

select * from table where (order_quantity > 0 or product_verified = false) and sku = "12345";

following is my code but i got a wrong result set 以下是我的代码,但是我得到了错误的结果集

Specification<JitOrderItem> specification = JitOrderItemSpecification.findAll();

specification = Specifications.where(specification).and(
                    Specifications.where(specification).or(JitOrderItemSpecification.filterByJitOrderQuantityGreaterThan(0))
                    .or(Specifications.where(specification).and(JitOrderItemSpecification.filterByProductVerified(false)))

                );
specification = Specifications.where(specification).and(JitOrderItemSpecification.filterBySku(sku));

I'm assuming you are using JPA, probably hibernate. 我假设您正在使用JPA,可能处于休眠状态。 You could enable Logging (for hibernate it's "org.hibernate.sql" to debug). 您可以启用日志记录功能(对于休眠模式,它是“ org.hibernate.sql”进行调试)。 That way you could see the generated query, which might help you in debugging these yourself. 这样,您可以看到生成的查询,这可以帮助您自己调试这些查询。

Looking at your code, your final specification would look something like this: 查看您的代码,最终的规范如下所示:

Specifications.where(
    Specifications.where(JitOrderItemSpecification.findAll())
        .and(
            Specifications.where(JitOrderItemSpecification.findAll())
                .or(JitOrderItemSpecification.filterByJitOrderQuantityGreaterThan(0))
                .or(Specifications.where(JitOrderItemSpecification.findAll()).and(JitOrderItemSpecification.filterByProductVerified(false)))
        )
)
.and(JitOrderItemSpecification.filterBySku(sku));

You are basically querying the following (WHERE clause only): 您基本上是在查询以下内容(仅WHERE子句):

(
    ALL JitOrderItems
    AND
    (
        ALL JitOrderItems
        OR 
        OrderQuantityGreaterThan 0
        OR 
        (
            ALL JitOrderItems
            AND
            ProductVerified false
        )
    )
)
AND
JitOrderItemSpec.filterBySku(sku)

What you want probably is the following: 您想要的可能是以下内容:

Specifications.where(
    JitOrderItemSpecification.filterByJitOrderQuantityGreaterThan(0).or(JitOrderItemSpecification.filterByProductVerified(false)))
    .and(JitOrderItemSpecification.filterBySku(sku));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM