节点MySQL复杂查询

节点MySQL复杂查询,mysql,node.js,Mysql,Node.js,MySQ中的My posts表的结构如下: 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 |

MySQ中的My posts表的结构如下:

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")
        }
    });
 });
app.get('/getposts',函数(req,res){
常量总计=“”,
connection.query(“从parentid=55的帖子中选择*”,函数(err,rows){
if(行数.长度){

total=rows.length/首先,我建议您使用一些ORM,比如Sequelize

无论如何,你要做的是计数、限制和偏移。所以

//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});
  })
})

正如你所看到的,这是混乱的,必须用一个前端来补充,该前端请求正确的页面和偏移量,还可以让用户知道基于
总数的结果更多。正如我所说的,我建议你使用一些ORM,sequelize工作得很有魅力。

你想做什么?分页?显示一些结果,让用户知道w还有更多?@yBrodsky yes..没错。看到了吗?这将只返回
parent_id=55
的行,从返回的行(
results
)中返回id(我们称之为
results.id
)应该在此处使用,并再次查询表中
parent\u id=results.id
的行。因此,我想我需要在某个地方使用
for loop
。我该怎么做?检查sequelize,感谢您参考它。我不完全理解您想要做什么。看起来您需要进行连接