简体   繁体   English

如何在sqlite3中实现嵌套查询

[英]How to implement nested query in sqlite3

So i have this 2-layer query in node.js, each query could return multiple results.所以我在 node.js 中有这个 2 层查询,每个查询可以返回多个结果。 My code actually just ignores that for now.我的代码实际上只是暂时忽略了这一点。 This is the best i can get, it seems working.这是我能得到的最好的,它似乎有效。

  1. How to correct it please, i don't know how to callback for the 2nd one.请如何更正,我不知道如何回调第二个。

  2. Also the db.close() is always called before the 2nd query finishes, even i have serialize().此外 db.close() 总是在第二个查询完成之前调用,即使我有 serialize()。

    var getInfo1Db = function(callback) { var db = new sqlite3.Database("DB.sqlite3"); var getInfo1Db = function(callback) { var db = new sqlite3.Database("DB.sqlite3");

     var cnt = 0; var info1JsonObj = []; db.all("select * from Info1DB", function(err, rows) { db.serialize(function() { for(var ii=0, len=rows.length; ii<len; ii++) { var t2 = rows[ii].info1; var doorId = ... db.all("select * from DoorDB where ObjectID=" + doorId, function(err, row2) { if(err) { } else { var doorName = row2[0]... var info1JsonElem = { "DoorName" : doorName }; info1JsonObj.push(info1JsonElem); cnt++; if(cnt === rows.length) { callback(null, info1JsonObj); } } } ); // for the only door info based on door id } // for each row of info1 db.close(); // why this finishes before the 2nd db.all } ); // end of serialize });

    }; };

How about using 2 function to do these ?使用 2 个函数来做这些怎么样?

function db_query1(your_param,...., callback){
  // database operation
   db.run( sql , [param,...] , function(err,rows){
      if(err) // return
      else{
         // get rows with callback
         callback(null, rows);
      }
   });
}

function db_query2(your_param,...., callback){
  // database operation
   db.run( sql , [param,...] , function(err,rows){
      if(err) // return
      else{
         // get rows with callback
         callback(null, rows);
      }
   });
}

And call these function:并调用这些函数:

db_query1(....,function(err,result1){
   if(err) ...// return 
   // do the things with result1
   // And then call query2
   db_query2(....,function(err,result2){
      if(err) ...// return 
      // do the things with result1
   });
});

Hope this will help :)希望这会有所帮助:)

You can use Promises.all , an array and the second callback for node sqlite3 db.each() that is executed when all rows have been fetched.您可以使用Promises.all ,一个数组和节点 sqlite3 db.each()的第二个回调,当所有行都被提取时执行。 Node Sqlite3 db.each usage to simplify the nested query and Node Sqlite3 db.each 用法,简化嵌套查询和

I cannot really get the meaning of the variables you are using thus I assume that each row in Info1DB has a one-to-many relationship with DoorDB on the field doorId .我真的不能得到你所使用的变量的含义因此,我认为在每一行Info1DB有一个一对多的关系DoorDB场上doorId

async function getInfo (callback) {
    sql = "select * from Info1DB;";
    numVersions = 0;
    countVersions = 0;
    info1JsonObj = [];
    db.serialize(function() {
        db.each(sql, [], (err, info1Row) => {
            sql = "select * from DoorDB where ObjectID=?;";
                info1Row.doors = [];
            doorId = ...
            db.each(sql, [doorId], (err, doorRow) => {
                info1Row.doors.push(new Promise((resolve, reject) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(doorRow);
                    }
                }));
            }, (err, num) => {
                Promise.all(info1Row.doors)
                    .then((doors) => {
                        info1Row.doors = doors;
                        info1JsonObj.push(info1Row);
                        countVersions++;
                        if (countVersions == numVersions) {
                            callback(null, info1JsonObj);
                        }
                    }).catch((err) => {
                        callback(err, null);
                    });
            });
        }, (err, versions) => {
            numVersions = versions;
        });
    });
}

You can't implement nested query in sqlite3's normal way.您不能以 sqlite3 的正常方式实现嵌套查询。 ( I mean you even can't do it in the callback hell way, because the sqlite3 need to close the connection before another query called. otherwise you will always got error) (我的意思是你甚至不能以callback hell方式做到这一点,因为sqlite3需要在调用另一个查询之前关闭连接。否则你总是会出错)

You have to use Promise , async and await to do this.你必须使用Promiseasyncawait来做到这一点。 ( it's worth to spend 30 minutes to learn these 3 words ) (花30分钟学习这3个词是值得的)

Step1.步骤一。 define a async function like this:像这样定义一个异步函数:

async query_1() {
  new Promise(resolve => {

      db = ...
      db.serialize( () => {
        db.get('select .. from ... where id = 1', [], (error, row) => {
           // here is the KEY: put the result into resolve 
           // this equals to the "return" statement in non-sync method.
           resolve(row)
        }
      })
      db.close()
  })
}

and also implement your query_2 function like this:并像这样实现你的 query_2 函数:

async query_2() {
  let query_1_result = await this.query_1()

  db = ...
  db.serialize( () => {
    db.get('select .. from ... where dependency_id = ' + query_1_result, [], (error, row) => {
       // other code here...
    }
  })
  db.close()
}

refer to my answer: https://stackoverflow.com/a/67881159/445908参考我的回答: https : //stackoverflow.com/a/67881159/445908

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM