【问题标题】:How to get data from DB (Postgres) in the same order as user input?如何以与用户输入相同的顺序从数据库(Postgres)获取数据?
【发布时间】:2020-10-27 14:13:57
【问题描述】:

我有一个文本区域,用户可以在其中输入以逗号分隔的单词。对于每个单词,我都会从我的 postgres 数据库中获得一个翻译(数据)。然后将输入以及来自数据库的翻译显示在一个表格中。

我的问题: 我需要在我的表中保持用户输入的顺序。但是顺序会根据我的数据库中单词的顺序自动更改。我尝试使用 ORDER BY,但无法修复。

有人能解释一下为什么订单会发生变化以及如何解决吗?非常感谢!

这是我的代码:

const getTranslation = async(req, res) => {
  const params = typeof req.query.word === 'string' ? req.query.word : req.query.word.map((_, index) => `$${index + 1}`);
  console.log(req.query.word);
  
  const rawResults = await pool.query(
    `SELECT "Translation", "Words" FROM "Dictionary" WHERE "Words" IN (${typeof req.query.word === 'string' ? '($1)' : params.join(
      ",")})`,
     typeof req.query.word === 'string' ? [req.query.word] : req.query.word, 
     (error, result) => {
      if (error) {
        throw error;
      }
      
      res.status(200).json(result.rows); 
      console.log(result.rows);
      }
  );

  const wordOrder = req.query.word.split(',');
  
  rawResults.sort((row1, row2) => {
      return wordOrder.indexOf(row1.Words) - wordOrder.indexOf(row2.Words);
    })
}

/*terminal console.log(req.query.word) is ['yes', 'no']
terminal console.log(result.rows) is [ {'Translation': 'non', 'Words': 'no'}, {'Translation': 'oui', 'Words': 'yes'}] */

【问题讨论】:

    标签: javascript sql postgresql input


    【解决方案1】:

    在作为响应发送之前重新排序。 从数据库中获取键及其翻译值,然后在结果上应用sort。

    const getTranslation = (req, res) => {
      const params =
        typeof req.query.word === 'string'
          ? req.query.word
          : req.query.word.map((_, index) => `$${index + 1}`);
      console.log(req.query.word);
    
      const rawResults = pool.query(
        `SELECT "Translation", "Words" FROM "Dictionary" WHERE "Words" IN (${
          typeof req.query.word === 'string' ? '($1)' : params.join(',')
        })`,
        typeof req.query.word === 'string' ? [req.query.word] : req.query.word,
        (error, result) => {
          if (error) {
            throw error;
          }
          const wordOrder = req.query.word.split(',');
    
          result.rows.sort((row1, row2) => {
            return wordOrder.indexOf(row1.Words) - wordOrder.indexOf(row2.Words);
          });
    
          res.status(200).json(result.rows);
          console.log(result.rows);
        }
      );
    };
    

    编辑

    注意您的代码是异步(数据库访问本质上是异步的)。 因此,您需要在将结果发送给客户端之前(就在res.status(200).json 调用之前)对结果进行排序

    顺便说一句,最好使用某种查询构建器(如knex)而不是手动构建查询。

    【讨论】:

    • 谢谢!我刚刚在我的问题中编辑了代码。当我 console.log 结果我得到一个数组......但即使我使用 .slice 而不是 .split 我得到一个“TypeError:无法读取未定义的属性'排序'”。你能帮我解决这个问题吗?
    • 我刚刚在我的问题中添加了代码。你是说这部分吗?
    • 非常感谢。我不得不删除 .split(',') -“TypeError: req.query.ingredient.split is not a function”。我想是因为 .split() 用于字符串。现在一切正常!据我了解:我们通常不使用异步...等待数据库查询,因为它默认是异步的,而我遇到的问题可能是因为我没有定义如何返回行并且系统使用最快这样做的方法。我说的对吗?
    • 我已经删除了Async & await 的使用,因为您正在处理回调。您的初始代码的问题是由于您的代码在异步回调之外。顺便说一句,考虑 knex 作为手动构建查询的替代方案。
    • 我认真对待您的提示并尝试了 knex...“仅”使用了 1 天 :D 如果您有兴趣为我指明正确的方向,我将不胜感激 :) stackoverflow.com/questions/64589169/…
    猜你喜欢
    • 2016-07-10
    • 2022-01-06
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 2011-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多