节点MySQL复杂查询

时间:2017-09-18 18:44:54

标签: mysql node.js

MySQ中的帖子表格结构如下:

id | title    | parentid
------------------------
1  | title 1  |   55
2  | title 2  |   55
3  | title 3  |   55
4  | title 4  |   1
5  | title 5  |   1
6  | title 6  |   1
7  | title 7  |   1
8  | title 8  |   1
9  | title 9  |   2
10 | title 10 |   2
11 | title 11 |   2
12 | title 12 |   1
13 | title 12 |   2
14 | title 12 |   2
15 | title 12 |   3
16 | title 12 |   1
17 | title 12 |   3
18 | title 12 |   2
19 | title 12 |   3
20 | title 12 |   1
21 | title 12 |   2

从节点I查询:

app.get('/getposts', function(req, res){

    const total = '',

    connection.query("SELECT * FROM posts WHERE parentid = 55", function (err, rows){

        if(rows.length) {
            total = rows.length    // <= Set Value for total posts.

            connection.query("SELECT * FROM posts WHERE parentid = 55 LIMIT 3", function (err, newrows){

            if(newrows.length) {

                if(newrows.length < total ){

                    var moreData = "Available";

                    var toSend = {newrows:newrows, moreData:moreData};

                    res.send(toSend) // <= Top 3 rows will be returned.

                }

                else{
                    res.send(newrows)   // <= Top 3 rows will be returned.
                }

            }

            })
        }
        else {
        res.send("NO DATA")
        }
    });
 });

这将给我前3行。现在,根据返回的行,我想获取更多数据,其中parentid等于返回的rows.id

因此,在应用LIMIT = 3后,将返回parentid=55的所有行,并且还应返回带有parentid = returnedRows.id的行以及moreData值。我可以在提及的响应中绑定moreData,但是无法构建查询以根据第二个查询中id的{​​{1}}提取更多数据。

请帮忙。非常感谢。

1 个答案:

答案 0 :(得分:0)

首先,我建议你使用一些ORM。像Sequelize http://docs.sequelizejs.com/

无论如何,你要做的就是计算,限制和抵消。所以....

//this variables you will get from the front and will need to be sanitized. This is merely an example.
let pageSize = 10, offset = 0
connection.query("SELECT COUNT(id) FROM posts WHERE parent_id = 55", (err, total) => {
  connection.query(`SELECT * FROM posts WHERE parent_id = 55 LIMIT ${pageSize}, ${offset}`, (err, results) => {
    return res.send({total, results});
  })
})

如您所见,这很麻烦,必须补充前端请求正确的页面和偏移量,并让用户知道基于total的更多结果。正如我所说,我建议你使用一些ORM,续集的作品就像一个魅力。