首页 > 解决方案 > SQLITE 查询的“排序依据”结果未排序

问题描述

我正在做一个网上商店项目。我正在尝试根据 sqlite 数据库中的参数值获取排序结果。我正在尝试根据“选择”值对产品进行排序。

在我的 app.js

app.get('/sortMaleProducts', function(request, response){

    var sortValues = request.query.sortValue;

    if(sortValues == 'priceASC')
    {
        sortValues = ["man", "price", "ASC"];
    }
    else if(sortValues == 'priceDESC')
    {
        sortValues = ["man", "price", "DESC"];
    }

    db.sortMaleProducts(sortValues, function(error, clothes){
        if(error){

            console.log("Error: "+ error);
        }
        else{

            console.log(clothes)
            const model = {

                clothes
            }

            response.render("man.hbs", model)
        }
    })
})

在我的 db.js

exports.sortMaleProducts = function(sortValues, callback){

    const query = 'SELECT * FROM products WHERE gender = ? Order by ?, ?'

    db.all(query, sortValues, function(error, clothes){

        console.log(clothes);
        callback(error, clothes);
    })

如果我对查询进行硬编码,例如:

const query = 'SELECT * FROM products WHERE gender = 'man' Order by price ASC'

然后它就可以工作了……但是我想使用用户输入,这样我就可以重用代码……

标签: javascriptnode.jssqliteexpress

解决方案


如果要按列排序,则该列名必须直接出现在查询中。您正在执行的操作按字符串'price'和对结果进行排序'ASC',这对于每一行都是相同的,因此对结果的任何顺序都进行了排序。

您也不能在查询中的其他任何地方使用列名作为参数,例如在要返回的列中或在WHERE. 当通过将语句编译成 sqlite 的内部字节码来准备语句时,它们必须存在,这发生在任何参数绑定或执行查询之前。


推荐阅读