我有select
个查询,我想添加filter
和search
值以选择查询。用户可以单独进行搜索,也可以一起进行过滤。以下是场景:
仅应用搜索(成功)时
select name, id from master.contact where name ilike 'sal%' or name ilike 'man%';
当我仅应用第一个过滤器(成功)
select name, id from master.contact where isActive=true;
同时应用两个过滤器(成功)
select name, id from master.contact where isActive=true and pan='abcd';
当我仅应用第二个过滤器(失败)
select name, id from master.contact and pan='abcd';
当我应用搜索并同时使用两个过滤器时(失败)
select * from master.contact where name ilike 'sal%' or name ilike 'man%' where master.contact.is_active = true and pan='abcd';
当我应用搜索和第一个过滤器(失败)
select * from master.contact where name ilike 'sal%' or name ilike 'man%' where master.contact.is_active = true;
nodejs
const query = {
text: `
select master.contact.id,
master.contact.name
from
master.contact
`
};
if (input.search) {
query.text += ` where
(master.contact.pan ILIKE '${input.search}%' or master.contact.ira ILIKE '${input.search}%')`;
}
if (input.filters) {
const {
isActive,
pan
} = input.filters;
if (isActive !== undefined) {
query.text += ` where master.contact.isActive = ${isActive}`;
}
if (pan) {
query.text += `and master.contact.pan = ${pan}`;
}
答案 0 :(得分:1)
如何在数组中收集条件,然后将其加入并附加,如下所示:
const query = {
text: `
select master.contact.id,
master.contact.name
from
master.contact
`
};
// Create an array to store any criteria
var where = [];
if (input.search) {
where.push(`(master.contact.pan ILIKE '${input.search}%' or master.contact.ira ILIKE '${input.search}%')`);
}
if (input.filters) {
const {
isActive,
pan
} = input.filters;
if (isActive !== undefined) {
where.push(`master.contact.isActive = ${isActive}`);
}
if (pan) {
where.push(`master.contact.pan = ${pan}`);
}
// If criteria were added, append to query text
if (where.length > 0) {
query.text += ' where ' + where.join(' and ');
}