链接承诺中的三个查询

时间:2019-06-11 07:00:35

标签: javascript sql node.js

我如何将这三个查询链接在一起以实现承诺?他们还会一个接一个地运行还是并行运行?

SELECT * FROM books where book_id = $1

SELECT * FROM username where username = $2

SELECT * FROM saved where saved_id = $3

编辑:

我不知道我应该为函数getBookIdQuery返回什么。它给出了错误:

  

getBookIdQuery不是函数

function getBookIdQuery(){
    return client.query(getBookId, [bookId]);
 }

那么我应该为该函数返回什么以便使链接有效?

return new Promise((resolve, reject) => {



        getBookIdQuery
        .then(data => {


        })
        .catch(err => {
            reject(err);
        });

});

2 个答案:

答案 0 :(得分:1)

不确定所使用的数据库。但总的来说,您可以根据需要以串行或并行方式执行查询。

Serial:

async serial(){
    queryResult1 = await client.query('SELECT * FROM books where book_id = $1', ['bookid']);
    queryResult2 = await client.query('SELECT * FROM username where username = $2',['username']);
    queryResult3 = await client.query('SELECT * FROM saved where saved_id = $3',['saved_id']);
    console.log(queryResult1);
    console.log(queryResult2);
    console.log(queryResult3);
}


Parallerl:

async parallel(){
   Promise.all([client.query('SELECT * FROM books where book_id = $1', ['bookid']), client.query('SELECT * FROM username where username = $2',['username']), client.query('SELECT * FROM saved where saved_id = $3',['saved_id']))
   .then(queryResults => {
        console.log(queryResults[0]);
        console.log(queryResults[1]);
        console.log(queryResults[2]);
   })
}

答案 1 :(得分:0)

使用 UNION ,并且每个Select中的值必须具有相同的别名,例如:

SELECT id as value FROM books where book_id = $1
union
SELECT name as value FROM username where username = $2
union
SELECT identificator as value FROM saved where saved_id = $3