【问题标题】:Function to get rows from DB by multiple columns conditionally有条件地按多列从数据库中获取行的函数
【发布时间】:2018-11-14 18:11:33
【问题描述】:

假设我有一条/moviesGET 路线(它实际上不是电影,但这样解释会更容易)

在客户端,我有一个表格,我想根据下拉菜单过滤电影:

流派、年份、国家、类型(默认情况下它们都在ALL

这些也是movies 表的数据库中的列。我正在使用node-postgres

所以我的查询是这样的:

  const query = {
    text: 'SELECT * FROM movies WHERE genre = $1 AND year = $2 AND country = $3 AND type = $4',
    values: [genre, year, country, type],
  };

但是,如果用户没有从下拉列表中选择任何内容(它将是 ALL),这将不起作用

如果客户端发送ALL,那么最好的方法是什么,它只是不将该列添加到查询中?

【问题讨论】:

    标签: javascript node.js postgresql express node-postgres


    【解决方案1】:

    我认为你别无选择,你应该只在适用的情况下提出你的条件......

    例如:

    const params = {
        genre: null,
        year: 2015,
        country: null,
        type: 'western',
    };
    
    const query = {
        text: 'SELECT * FROM movies',
        values: Object.values(params).filter(x => x),
    };
    
    if (Object.values(params).filter(x => x).length) {
        query.text += ' WHERE '
        let i = 1;
        for (const param of Object.keys(params).filter(x => params[x])) {
            query.text += `${param} = $${i} AND `
            i++;
        }
        query.text = query.text.substr(0, query.text.length - 5);
    }
    
    console.log(query); // {"text":"SELECT * FROM movies WHERE year = $1 AND type = $2","values":[2015,"western"]}
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2013-06-16
      • 1970-01-01
      • 1970-01-01
      • 2015-12-06
      • 1970-01-01
      • 2015-10-21
      • 1970-01-01
      • 2020-04-19
      • 2014-05-23
      相关资源
      最近更新 更多