【问题标题】:How do I select a column using an alias如何使用别名选择列
【发布时间】:2015-12-15 10:30:20
【问题描述】:

如何执行这样的 sql 查询?

SELECT column_name AS alias_name FROM table_name;

示例:我希望将“first”列选为“firstname”

Table.findAll({
      attributes: [id,"first"]
    })
    .then(function(posts) {
        res.json(posts);
    })

【问题讨论】:

    标签: javascript sql sequelize.js


    【解决方案1】:

    您需要使用row.get('newname') 访问以attributes 为别名的列

    出于某种原因,仅使用 row.newnamerow.oldname 不会像处理非别名名称那样工作:

    相关:Sequelize cannot access alias. Alias is undefined

    最小的可运行示例:

    const assert = require('assert');
    const path = require('path');
    const { Sequelize, DataTypes, Op } = require('sequelize');
    const sequelize = new Sequelize({
      dialect: 'sqlite',
      storage: path.basename(__filename) + '.sqlite',
    });
    (async () => {
    const Int = sequelize.define('Int', {
      value: {
        type: DataTypes.INTEGER,
      },
      name: {
        type: DataTypes.STRING,
      },
    }, {});
    await Int.sync({force: true})
    await Int.create({value: 2, name: 'two'});
    let row;
    row = await Int.findOne({
      where: { value: 2 },
      attributes: [ 'id', [ 'value', 'newvalue' ] ],
    });
    assert.strictEqual(row.id, 1);
    assert.strictEqual(row.value, undefined);
    assert.strictEqual(row.newvalue, undefined);
    assert.strictEqual(row.get('newvalue'), 2);
    await sequelize.close();
    })();
    

    生成的查询完全符合我们当时的要求:

    SELECT `id`, `value` AS `newvalue` FROM `Ints` AS `Int`
      WHERE `Int`.`value` = 2 LIMIT 1;
    

    在 sequelize 6.5.1、sqlite3 5.0.2 上测试。

    【讨论】:

      【解决方案2】:

      Sequelize 也支持直接在模型定义上定义列名。

      Sequelize Docs 他们在列定义中提到了field 属性。

      例如:(取自文档本身)

      const { Model, DataTypes, Deferrable } = require("sequelize");
      
      class Foo extends Model { }
      Foo.init({
          // You can specify a custom column name via the 'field' attribute:
          fieldWithUnderscores: {
              type: DataTypes.STRING, 
              field: 'field_with_underscores'
          },
      }, {
          sequelize,
          modelName: 'foo'
      });
      

      感谢this answer

      【讨论】:

        【解决方案3】:
        Table.findAll({
          attributes: ['id', ['first', 'firstName']] //id, first AS firstName
        })
        .then(function(posts) {
          res.json(posts);
        });
        

        【讨论】:

        • 它可以工作,但是在连接查询中使用时,它会将表名附加到给定的别名上。有没有办法去掉表名?
        • @antew 你可以在这里找到答案:stackoverflow.com/questions/50148491/…
        • 它在多级联接中不起作用。可以说,表 A 包括(表 B 包括表 C)。我无法选择表 B 中的表 C 列(它总是作为表 A 的前缀)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-28
        • 2020-10-26
        • 2012-03-23
        • 1970-01-01
        • 2022-11-12
        • 2011-11-10
        相关资源
        最近更新 更多