根据@variable根据IF条件执行不同的WHERE语句?

时间:2020-11-04 14:07:07

标签: mysql sql string spring-boot where-clause

我在Spring Boot应用程序的nativeQuery层中有一个DAO

基本上,我要传递三个参数,就像这样:

@Query(name = "findInvoicesTour", nativeQuery = true)
    List<InvoiceDto> findInvoices(@Param("invoiceNumber") String invoiceNumber, @Param("companyName") String companyName, @Param("paid") boolean paid);

我想根据companyName的值执行不同的WHERE语句,如下所示:

if(:companyName = '')
    SELECT col1, col2, col3
    FROM invoice_tour it
    WHERE it.paid =: paid AND it.invoice_number LIKE :invoiceNumber
ELSE
    SELECT col1, col2, col3
    FROM invoice_tour it
    WHERE it.paid =: paid AND it.invoice_number LIKE :invoiceNumber AND it.companyName := companyName

SELECT col1, col2, col3
 if(:companyName = '')
        FROM invoice_tour it
        WHERE it.paid =: paid AND it.invoice_number LIKE :invoiceNumber
 ELSE
        FROM invoice_tour it
        WHERE it.paid =: paid AND it.invoice_number LIKE :invoiceNumber AND it.companyName := companyName

1 个答案:

答案 0 :(得分:1)

使用布尔逻辑:

SELECT col1, col2, col3
FROM invoice_tour it
WHERE 
    it.paid =: paid 
    AND it.invoice_number LIKE :invoiceNumber
    AND (:companyName = '' OR it.companyName := companyName)