sequelize query select*from table只返回一行

eit6fx6z  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(365)

我目前正在使用postgresql和sequelize.js来查询一些数据。当我使用sequelize.query()时,它只返回一行数据,但当我通过pgadmin输入数据时,它会正常工作。
下面是我在sequelize.query()中使用的代码。

SELECT table2.student_id,
          s.canvasser_name,
          l.level_name,
          table2.total_score
   FROM (SELECT table1.student_id,
                sum(table1.max_score) total_score
         FROM (SELECT sq.student_id,
               max(sq.score) max_score
               FROM public.student_quiz sq
               GROUP BY sq.quiz_id, sq.student_id) table1
         GROUP BY table1.student_id) table2
   INNER JOIN public.student s
           ON s.id = table2.student_id
   INNER JOIN public.level l
           ON l.id = s.level_id
   ORDER BY table2.total_score DESC
   LIMIT 10;

这是nodejs代码

const getRank = (option, logs = {}) => new Promise(async (resolve, reject) => {
  try {
    let { offset, limit } = option;
    if (!limit) limit = 10;
    const result = await sequelize.query(
      `SELECT table2.student_id,
              s.canvasser_name,
              l.level_name,
              table2.total_score
       FROM (SELECT table1.student_id,
                    sum(table1.max_score) total_score
             FROM (SELECT sq.student_id,
                   max(sq.score) max_score
                   FROM public.student_quiz sq
                   GROUP BY sq.quiz_id, sq.student_id) table1
             GROUP BY table1.student_id) table2
       INNER JOIN public.student s
               ON s.id = table2.student_id
       INNER JOIN public.level l
               ON l.id = s.level_id
       ORDER BY table2.total_score DESC
       LIMIT 10;`,
      { plain: true }
    );

    return resolve(result);
  } catch (error) {
    let customErr = error;
    if (!error.code) customErr = Helpers.customErrCode(error, null, undefinedError);
    logger.error(logs);
    return reject(customErr);
  }
});

下面是使用上述函数的代码

const getRankController = async (req, res) => {
  try {
    const { offset, limit } = req.query;
    const result = await getRank({ offset, limit });

    if (result.length < 1) {
      return Helpers.response(res, {
        success: false,
        message: 'cannot get score list'
      }, 404);
    }

    return Helpers.response(res, {
      success: true,
      result
    });
  } catch (error) {
    return Helpers.error(res, error);
  }
};

同时,我正在尝试使用sequelize内置函数的另一种方法,下面是代码。

const getRank = (
  option,
  logs = {}
) => new Promise(async (resolve, reject) => {
  try {
    // eslint-disable-next-line prefer-const
    let { offset, limit } = option;
    if (!limit) limit = 10;
    const result2 = await StudentQuiz.findAll({
      attributes: ['studentId', [sequelize.fn('sum', sequelize.fn('max', sequelize.col('score'))), 'totalPrice'], 'quizId'],
      group: 'studentId',
      include: [
        {
          model: Student,
          include: [{
            model: Level
          }],
        },
      ],
      offset,
      limit
    });

    return resolve(result2);
  } catch (error) {
    let customErr = error;
    if (!error.code) customErr = Helpers.customErrCode(error, null, undefinedError);
    logger.error(logs);
    return reject(customErr);
  }
});

这一个不工作,因为它是嵌套函数,我有点不明白如何复制它。
我试着做一些简单的查询,比如selectfrom table,它返回一行,然后我发现我需要在表名中添加“public”,这样它就变成selectfrom public.table了。好吧,在我尝试第二个代码块的代码之前。
任何回答或建议将不胜感激,谢谢。

9cbw7uwe

9cbw7uwe1#

我想您需要指示一个查询类型并删除 plain: true 选项如下:

const result = await sequelize.query(
      `SELECT table2.student_id,
              s.canvasser_name,
              l.level_name,
              table2.total_score
       FROM (SELECT table1.student_id,
                    sum(table1.max_score) total_score
             FROM (SELECT sq.student_id,
                   max(sq.score) max_score
                   FROM public.student_quiz sq
                   GROUP BY sq.quiz_id, sq.student_id) table1
             GROUP BY table1.student_id) table2
       INNER JOIN public.student s
               ON s.id = table2.student_id
       INNER JOIN public.level l
               ON l.id = s.level_id
       ORDER BY table2.total_score DESC
       LIMIT 10;`,
      { 
        type: Sequelize.QueryTypes.SELECT
      }
    );

从sequelize文档:

options.plain - Sets the query type to SELECT and return a single row

相关问题