根据@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语句?的主要内容,如果未能解决你的问题,请参考以下文章

如何根据不同的条件执行不同的SQL语句

SQL根据条件执行不同的语句

hive 如何使用条件语句根据结果执行不同的查询

Dialogflow:根据值和其他条件响应进行响应

mysql根据条件执行sql

JS语句和数组