【发布时间】:2021-07-24 10:33:57
【问题描述】:
我是 Node、API 和 SQL 的新手,我碰壁了。我正在使用pg-promise 准备好的语句,我正在尝试使用sorted 参数和ORDERED BY 命令对结果进行通常的排序,但它不起作用,因为总是按相同的顺序排列。
如果我直接使用参数的名称,它会起作用,你能看到我的查询做错了什么吗?
像往常一样非常感谢您的时间和帮助。
这是我的方法:
if (city, region, country, category, minPrice, maxPrice, orderedBy, sorted) {
if (sorted == 'asc') {
await db.any({
name: 'get-city-category-price-range-ordered-by-asc-products',
// text: 'SELECT * FROM products WHERE city = $1 AND region = $2 AND country = $3 AND category = $4 AND price >= $5 AND price <= $6 ORDER BY price ASC', // working
text: 'SELECT * FROM products WHERE city = $1 AND region = $2 AND country = $3 AND category = $4 AND price >= $5 AND price <= $6 ORDER BY $7 ASC', // not working
values: [city, region, country, category, minPrice, maxPrice, orderedBy]
})
.then(result => {
console.log('get-city-category-price-range-ordered-by-asc-products:', result);
if (result.length > 0) {
res.status(200).send({
data: result
});
}
else {
res.status(404).send({
error: 'No product found.'
});
}
})
.catch(function (error) {
console.log('get-city-category-price-range-ordered-by-asc-products error:', error);
});
} else if (sorted == 'desc') {
await db.any({
name: 'get-city-category-price-range-ordered-by-desc-products',
// text: 'SELECT * FROM products WHERE city = $1 AND region = $2 AND country = $3 AND category = $4 AND price >= $5 AND price <= $6 ORDER BY price DESC', // working
text: 'SELECT * FROM products WHERE city = $1 AND region = $2 AND country = $3 AND category = $4 AND price >= $5 AND price <= $6 ORDER BY $7 DESC', // not working
values: [city, region, country, category, minPrice, maxPrice, orderedBy]
})
.then(result => {
console.log('get-city-category-price-range-ordered-by-desc-products:', result);
if (result.length > 0) {
res.status(200).send({
data: result
});
}
else {
res.status(404).send({
error: 'No product found.'
});
}
})
.catch(function (error) {
console.log('get-city-category-price-range-ordered-by-desc-products error:', error);
});
}
}
【问题讨论】:
标签: node.js postgresql pg-promise