javascript - 对 javascript 对象的复杂 SQL 查询

标签 javascript sql

我有以下 JS 对象:

var groups = [{id="4", name="abcd", id_group="1"},
              {id="5", name="efgh", id_group="1"},
              {id="6", name="ijkl", id_group="1"},
              {id="4", name="abcd", id_group="2"},
              {id="7", name="mnop", id_group="2"}]

我需要对上述对象执行此 SQL 查询:

select id_group from groups where id in (4,7) 
group by id_group having count(distinct id) = 2

结果应该是:

id_group="2"

因为只有该组包含查询中使用的两个 ID。

我找到了关于 SQLike 的信息和 JSLINQ但我遇到了where inhaving 表达式的问题。是否有可能使用 SQL-JS 库或 JS/jQuery 本身(编写函数等)对 javascript 对象执行此类查询?

最佳答案

Alasql JavaScript SQL 库专为此类任务而设计:

<script src="alasql.min.js"></script>
<script>
    var groups = [{id:4, name:"abcd", id_group:"1"},
          {id:5, name:"efgh", id_group:"1"},
          {id:6, name:"ijkl", id_group:"1"},
          {id:4, name:"abcd", id_group:"2"},
          {id:7, name:"mnop", id_group:"2"}];

    var res = alasql('select id_group, count(id) as cnt from ? \
        where id in (4,7) group by id_group having cnt = 2',[groups]); 
</script>

你可以试试this example在 jsFiddle 中。

我修改了一点 SQL 表达式,因为 Alasql 不支持 HAVING 子句中的聚合函数(如 COUNT、SUM、MAX、MIN)。

关于javascript - 对 javascript 对象的复杂 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18052645/

相关文章:

javascript - 如果输入文件在没有表单的ajax请求中作为数组元素传递,为什么数组对象变为空

javascript - 使用 Resources 制作不带引号的 JSON

javascript - 与在单独的 .js 文件中保留 Jquery 相关的问题

javascript - Mootools:将 HTML 文本添加到元素

mysql - 使用 JOINS、ORDER BY 和数据透视表

mysql - 如何查询连通坐标?

javascript - 如何从 excel 文件中获取输入并在速度计上显示输出

sql - Postgresql:如何确保索引在内存中

Mysql 每月分区 - 错误代码 : 1503 A PRIMARY KEY must include all columns in the table's partitioning function

php - 连接 Php、html 和 mysql