【问题标题】:how to count all empty cells in a table with knexjs?如何使用 knexjs 计算表格中的所有空单元格?
【发布时间】:2019-08-20 03:26:46
【问题描述】:

我有一个包含多行的表格,每行都有空单元格,我正在尝试将每行中的所有空单元格计数为总数。

table schema id , name, colmn1 , colmn2, colmn3, colmn4, etc.... 直到 colmn20

我试过做这样的事情

knexDb('users').where(function() {
    this.where('colmn1', '=', '')
    .orWhere('colmn2', '=', '')
    .orWhere('colmn3', '=', '')
    .orWhere('colmn4', '=', '')
    .orWhere('colmn5', '=', '')
    .orWhere('colmn6', '=', '')
    .orWhere('colmn7', '=', '')
    .orWhere(........ etc till colmn20
  })
  .map(function(row) {
    // console.log(row)
    var emptycolmns = 0;
    if(row.colmn1 === ''){
      emptycolmns++
    }else if (row.colmn2 === ''){
      emptycolmns++
    }else if ....... etc till colmn20
  })
  .then(rows => {
    console.log(rows);
    console.log(emptycolmns);
  })

但这对我不起作用。

附言。如您所见,对所有列进行硬编码并不好,是否有更好的方法来实现这两种结果,并提供更好的解决方案。

【问题讨论】:

    标签: knex.js


    【解决方案1】:

    我能想到的最接近的计算空字符串列的方法是:

    knex.raw(
      `select (col1='') + (col2='') + (col3='') as empty_cols from foo`
    )
    

    在这里,您依赖于每个表达式都将解析为整数的事实,因此最后您会得到如下结果:

    empty_cols
    ==========
    1
    3
    2
    3
    1
    

    正如您所指出的,它似乎不太灵活,但是如果不了解问题的更多信息,就很难就首选架构提出建议。

    【讨论】:

      猜你喜欢
      • 2021-11-07
      • 2022-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-24
      相关资源
      最近更新 更多