2

我有一个数据库,我会举一个例子。

guildid    botid
1234       ["2345","3456","3714","1812"]
9876       ["8765","5432"]
4346       NULL
2371       ["3179"]
1254       NULL
1257       ["1721","7104","8265"]
8321       NULL

我需要输出 botid 的数量,在本例中为 answer = 10。数据库中有 7 条记录,但总共有 10 个不为 NULL 的 id 通常我会这样做SELECT count(*) FROM watchedbots但是这只计算有多少条记录。在某些情况下,botid 也可以NULL,所以我需要它来忽略 NULL 条目。在阵列方面我是相当新的,所以任何帮助都将不胜感激。我用于 SQL 的模块是better-sqlite3

编辑:扩展示例

如果我执行以下操作:

const dataGrab = db.prepare('SELECT botid FROM watchedbots').all()
const stringify = JSON.stringify(dataGrab)
console.log(stringify)

我得到一个输出: [{"botid":null},{"botid":null},{"botid":null},{"botid":"["1721","7104","8265"]"},{"botid":"["2345","3456","3714","1812"]"},{"botid":"["3179"]"},{"botid":"["8765","5432"]"}] 我猜这是一个很好的下一步,但不知道我会从那里去。

4

1 回答 1

1

我认为您最简单的方法是遍历基本数组。

let count = 0;
for(guild of dataGrab) {
    if(guild.botid) {
        let arr = guild.botid.slice(1, guild.botid.length -1).split(',');
        count += arr.length;
    }
}
console.log(count);
于 2020-04-02T21:28:11.427 回答