【问题标题】:How to do recursive queries on two tables using web sql database?如何使用 web sql 数据库对两个表进行递归查询?
【发布时间】:2011-07-07 23:35:10
【问题描述】:

我在一个使用 web sql 数据库的 html5 项目中。

我有 2 张桌子。

产品表

  • 身份证
  • 姓名

价格表

  • 身份证
  • product_id
  • 日期
  • 价格

一个产品可以有多个不同日期的价格。

我试过类似的东西:

bd.x.transaction(function (tx) {
    tx.executeSql('SELECT * FROM Products WHERE id = ?', intProductId,
        function (tx, rs) {
            if (rs.rows.length > 0) {
                var objProduct = new clsProduct();
                objProduct.setId(rs.rows.item(0).id);
                objProduct.setName(rs.rows.item(0).name);

                // Query Price Start
                bd.x.transaction(function (tx) {
                    tx.executeSql('SELECT * FROM Prices WHERE product_id = ?', intProductId,
                        function (tx, rs) {
                            var x = rs.rows.length;
                            if (x > 0) {
                                var arrResult = [];
                                for (var i = 0; i < x; i++) {
                                    arrResult[i] = new clsPrice();
                                    arrResult[i].setId(rs.rows.item(i).id);
                                    arrResult[i].setDate(rs.rows.item(i).date);
                                    arrResult[i].setPrice(rs.rows.item(i).price);
                                }

                                // set prices
                                objProduct.setPrice(arrResult);
                            }
                        },
                        bd.onError
                    );
                });
                // Query Price End
            }
        },
        bd.onError
    );
});

问题是 Product 查询在 Price 查询完成之前完成,并且 objProduct.getPrice() 返回 undefined。

如果我在价格查询中添加警报,则会找到记录并且我可以看到结果。

我该怎么做?

谢谢。

【问题讨论】:

    标签: javascript database html


    【解决方案1】:

    您想使用复合查询,其中 SQL 类似于:

    SELECT * FROM Products WHERE id IN (SELECT * FROM Prices WHERE product_id = ?)
    

    这样你只执行一个查询;从 SQL 的角度来看,它会更好。

    【讨论】:

    • 你是对的。我非常担心 HTML5 的新可能性,以至于我忘记了旧的解决方案。感谢您记住,世界不仅在转向 HTML5。呵呵:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多