根据@variable,根据IF条件执行不同的WHERE语句?
Posted
技术标签:
【中文标题】根据@variable,根据IF条件执行不同的WHERE语句?【英文标题】:Execute different WHERE statement based on IF conditions depending on @variable? 【发布时间】:2021-02-17 05:44:04 【问题描述】:我的 Spring Boot 应用程序中的 DAO
层中有一个 nativeQuery
。
基本上,我传递三个参数,如下所示:
@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】:使用布尔逻辑:
SELECT col1, col2, col3
FROM invoice_tour it
WHERE
it.paid =: paid
AND it.invoice_number LIKE :invoiceNumber
AND (:companyName = '' OR it.companyName := companyName)
【讨论】:
以上是关于根据@variable,根据IF条件执行不同的WHERE语句?的主要内容,如果未能解决你的问题,请参考以下文章