sequelize 查询示例

优质
小牛编辑
140浏览
2023-12-01

sequelize 查询示例

const Op = Sequelize.Op

[Op.and]: {a: 5}           // 且 (a = 5)
[Op.or]: [{a: 5}, {a: 6}]  // (a = 5 或 a = 6)
[Op.gt]: 6,                // id > 6
[Op.gte]: 6,               // id >= 6
[Op.lt]: 10,               // id < 10
[Op.lte]: 10,              // id <= 10
[Op.ne]: 20,               // id != 20
[Op.eq]: 3,                // = 3
[Op.not]: true,            // 不是 TRUE
[Op.between]: [6, 10],     // 在 6 和 10 之间
[Op.notBetween]: [11, 15], // 不在 11 和 15 之间
[Op.in]: [1, 2],           // 在 [1, 2] 之中
[Op.notIn]: [1, 2],        // 不在 [1, 2] 之中
[Op.like]: '%hat',         // 包含 '%hat'
[Op.notLike]: '%hat'       // 不包含 '%hat'
[Op.iLike]: '%hat'         // 包含 '%hat' (不区分大小写)  (仅限 PG)
[Op.notILike]: '%hat'      // 不包含 '%hat'  (仅限 PG)
[Op.startsWith]: 'hat'     // 类似 'hat%'
[Op.endsWith]: 'hat'       // 类似 '%hat'
[Op.substring]: 'hat'      // 类似 '%hat%'
[Op.regexp]: '^[h|a|t]'    // 匹配正则表达式/~ '^[h|a|t]' (仅限 MySQL/PG)
[Op.notRegexp]: '^[h|a|t]' // 不匹配正则表达式/!~ '^[h|a|t]' (仅限 MySQL/PG)
[Op.iRegexp]: '^[h|a|t]'    // ~* '^[h|a|t]' (仅限 PG)
[Op.notIRegexp]: '^[h|a|t]' // !~* '^[h|a|t]' (仅限 PG)
[Op.like]: { [Op.any]: ['cat', 'hat']} // 包含任何数组['cat', 'hat'] - 同样适用于 iLike 和 notLike
[Op.overlap]: [1, 2]       // && [1, 2] (PG数组重叠运算符)
[Op.contains]: [1, 2]      // @> [1, 2] (PG数组包含运算符)
[Op.contained]: [1, 2]     // <@ [1, 2] (PG数组包含于运算符)
[Op.any]: [2,3]            // 任何数组[2, 3]::INTEGER (仅限PG)

[Op.col]: 'user.organization_id' // = 'user'.'organization_id', 使用数据库语言特定的列标识符, 本例使用 PG

数据表结构 | id | name | age | sex | address | math | english | | --- | --- | --- | --- | --- | --- | --- | | 张三 | 23 | 男 | 18 | 云南 | 60 | 40| | 李四 | 23 | 女 | 22 | 贵州| 20 | 30| | 王麻子 | 23 | 男 | 30| 玉溪 | 30 | 26| | 赵六 | 23 | 女 | 26 | 德州 | 80 | 38 | | 刘能 | 23 | 女 | 19 | 西凉 | 100| 48 | | 段鱼 | 23 | 男 | 28 | 广州 | 60| 52| | 琳娜 | 23 | 男 | 34 | 泰国 | 40| 46| | 贝利 | 23 | 男 | 42 | 美国 | 50| 69 | | 皮特 | 23 | 女 | 50 | 英国 | 38| 70 | | 汤姆 | 23 | 男 | 46 | 缅甸 | 42| 65 |


  • [ ] 查询年龄 > 20 的学生
    model.findAll({
      attributes: ['name', 'age'],
      where: {
          // age > 20
          age: {
          }
      }
    })

  • [ ] 查询年龄 > 20 && < 30 的学生
    model.findAll({
      attributes: ['name', 'age'],
      where: {
          age: {
              }
          }
      }
    })
    `student`.`age` &gt; 20 AND `student`.`age` &lt; 30

  • [ ] 查询年龄 in 28 26 52
    model.findAll({
      attributes: ['name', 'age'],
      where: {
          age: {
          }
      }
    });
    `student`.`age` IN (26, 28, 52)

  • [ ] 查询英语成绩为null的
    model.findAll({
      attributes:['name','english'],
      where: {
          english: {
          }
      }
    })
    `student`.`english` IS NULL

  • [ ] 查询英语成绩 IS NOT NULL 不为空
    Student.findAll({
      attributes:['name','english'],
      where: {
          english: {
          }
      }
    })
    `student`.`english` IS NOT NULL