Alasql - 在json中查询嵌套对象

时间:2016-03-12 17:18:08

标签: javascript sql json alasql

我有一个像下面这样的json对象。

易趣对象

    {
    __v: 0
    _id: "56e192f0aea7131c15513328"
    headquarters: "New York"
    name: "Ebay"
    productCategories: [{
        _id: "56e193beaea7131c1551332d"
        name: "Footwear"
        products: [{
            name: 'Shiela',
            price: 420,
            totalSales: [10, 20]
        }, {
            name: 'Parry',
            price: 350,
            totalSales: [50, 20]
        }]
        totalSales: 100
    }, {
        1: Object
        _id: "56e193beaea7131c1551332e"
        name: "Clothes"
        products: [{
            name: 'Kurta',
            price: 210,
            totalSales: [60, 80]
        }, {
            name: 'Sun Glass',
            price: 785,
            totalSales: [5, 25]
        }],
        totalSales: 170
    }]
}

亚马逊对象

{
        __v: 0
        _id: "56e192f0aea7131c15513328"
        headquarters: "New York"
        name: "Amazon"
        productCategories: [{
            _id: "56e193beaea7131c1551332d"
            name: "Footwear"
            products: [{
                name: 'Shiela',
                price: 280,
                totalSales: [10, 20]
            }, {
                name: 'Parry',
                price: 785,
                totalSales: [50, 20]
            }]
            totalSales: 100
        }, {
            1: Object
            _id: "56e193beaea7131c1551332e"
            name: "Clothes"
            products: [{
                name: 'Kurta',
                price: 150,
                totalSales: [60, 80]
            }, {
                name: 'Sun Glass',
                price: 485,
                totalSales: [5, 25]
            }],
            totalSales: 170
        }]
    }

我想在产品类别中选择两个公司共同的名称。

然后,我想选择常见产品类别中常见的产品。

然后我想得到普通产品(两家公司)的价格进行比较

我可以运行以下查询

 alasql('SELECT products FROM ? AS CATEGORY1 JOIN ? AS CATEGORY2 USING [0]', [$scope.company1.productCategories, $scope.company2.productCategories], function(data) {
                    console.log("join query executed");
                    console.log(data);
                });

我想在每个产品类别中找到产品。我想要一个像

这样的查询
alasql('SELECT products.name,products.price FROM ? as category1 join ? as category2 using products.name', [$scope.company1.productcategories,$scope.company2.productcategories], function(data) {
                    console.log("Query executed");
                    console.log(data);
                });

但这出错了。

请告诉我正确的程序。

此致 Sabarisri

1 个答案:

答案 0 :(得分:4)

首先,当您只处理本地内存时,有理由将其设为异步。所以你的第一个改变应该是使用

var res = alasql('SELECT productCategories->0->name FROM ?',[$scope.selectedCompanies]);

你非常接近。您基本上只想查询productCategories数据 - 所以您应该

var res = alasql('SELECT name FROM ?',[$scope.selectedCompanies.productCategories]);

奖励信息:如果您想加入某些内容,您可以执行类似

的操作
var res = alasql('SELECT p.name, d.stock FROM ? p JOIN ? d ON p.name = d.company',[$scope.selectedCompanies.productCategories, $scope.otherData]);