You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TS环境下Node/Sequelize/MySQL如何通过动态查询获取指定列全部值

可以实现,两种常用场景的实现方案如下:

方案1:仅获取指定列的全量值

如果不需要按行过滤,只需要取出目标字段的所有值,直接动态配置 attributes 配置项即可:

// 示例:客户端传入的查询参数为column=BTCUSDPrice
const targetColumn = req.query.column
// 先做白名单校验,避免非法字段查询
const allowedColumns = ['BTCUSDPrice', 'ETHUSDPrice', '其他允许查询的字段名']
if (!allowedColumns.includes(targetColumn)) {
  return res.status(400).json({msg: '非法查询字段'})
}

const records = await Crypto.findAll({
  attributes: [targetColumn] // 仅查询指定列
})

// 如果你只需要纯数值数组,不需要返回对象结构,额外做一次map即可
const valueList = records.map(item => item[targetColumn])

方案2:需要按动态字段做行过滤

如果除了指定返回列,还要按动态字段做筛选,用ES6计算属性语法即可实现动态where键名:

const targetColumn = req.query.column
const filterVal = req.query.filterVal // 比如要查BTCUSDPrice大于50000的所有值
const allowedColumns = ['BTCUSDPrice', 'ETHUSDPrice']
if (!allowedColumns.includes(targetColumn)) {
  return res.status(400).json({msg: '非法查询字段'})
}

const records = await Crypto.findAll({
  attributes: [targetColumn],
  where: {
    [targetColumn]: {
      [Op.gt]: filterVal // 也可以直接写固定匹配值,比如[targetColumn]: 50000
    }
  }
})

注意:所有动态传入的字段名必须做白名单校验,不能直接透传用户输入,避免出现SQL注入或敏感数据泄露问题

内容的提问来源于stack exchange,提问作者user16657995

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 03:24:02