正确实现
使用Case When来编写查询条件
SELECT * FROM pc_ticket_tax_cloud
WHERE 1=1
AND (CASE WHEN {{data_table.searchText != ''}} THEN xsddm like '{{data_table.searchText || ""}}%'ELSE 1=1 END
)
AND (CASE WHEN {{doc_code_input.text != ''}} THEN doc_code like '{{doc_code_input.text || ""}}%'ELSE 1=1 END
)
ORDER BY {{data_table.sortOrder.column || 'id'}} {{data_table.sortOrder.order || "DESC"}}
LIMIT {{data_table.pageSize}}
OFFSET {{(data_table.pageNo - 1) * data_table.pageSize}};
如下图:
当点击查询按钮时:
错误实现
可能有人会问为什么这么麻烦?不能如下查询么?
SELECT * FROM pc_ticket_tax_cloud
WHERE xsddm like '{{data_table.searchText || ""}}%'
and doc_code like '{{ doc_code_input.text || ""}}%'
ORDER BY {{data_table.sortOrder.column || 'id'}} {{data_table.sortOrder.order || "DESC"}}
LIMIT {{data_table.pageSize}}
OFFSET {{(data_table.pageNo - 1) * data_table.pageSize}};
不能!因为两个查询条件始终生效,比如不设置搜索条件时,实际的sql是:
SELECT * FROM pc_ticket_tax_cloud
WHERE xsddm like '%'
and doc_code like '%'
ORDER BY {{data_table.sortOrder.column || 'id'}} {{data_table.sortOrder.order || "DESC"}}
LIMIT {{data_table.pageSize}}
OFFSET {{(data_table.pageNo - 1) * data_table.pageSize}};
而doc_code是null的将不会查询到!因为null 不符合 like '%'的条件,但我们想要的是查询所有数据,因此不能这样做。