D
D
dmitriu2562020-05-05 16:26:29
JavaScript
dmitriu256, 2020-05-05 16:26:29

How to combine two queries COUNT and LIMIT?

What I want to get (uploading news by pressing a button)
Initially, I want to download three news from the server (express js), then by pressing a button, show another + 1 news.
When the news is the latest - hide the "Show more" button
(the logic on the client is clear)

Now queries the database
1) Get the number of records in the table
SELECT COUNT(*) FROM news

2) Set a limit on the selection
SELECT * FROM news LIMIT ${req.params .from}, ${req.params.lim}

Next, when the button is clicked, an AJAX request is made from the client and we change LIMIT

Server code

app.get('/news/:from/:lim', (req,res) => {
    connection.query(`SELECT  * FROM news LIMIT ${req.params.from}, ${req.params.lim}`, function(error, rows) {
        if(error) throw new  Error(error);
        res.json(rows);
    });
});

app.get('/news', (req,res) => {
    connection.query(`SELECT COUNT(*) FROM news `, function(error, rows) {
        if(error) throw new  Error(error);
        res.json(rows);
    });
});


The result is how to optimize queries,
Now the logic is as follows
1) Query with LIMIT 0.3 - loaded the first three news
2) Query to get the number of records in the COUNT table
3) Query by pressing the button - change LIMIT 4, 1
The next click will repeat steps 2 and 3(LIMIT 5,1)

Can all these actions be combined into one request?
How do I want to do
with each return of news, the server returns the total number of news (COUNT), the remaining number of news and the current serial number of the news (for use in LIMIT)

In this scenario, I will always know the serial number of the current news and LIMIT (news_now + 1) will not exceed COUNT.
Reduce the load on the server - instead of 3 requests there will be one
How to implement it?
I will be grateful for your help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
SagePtr, 2020-05-05
@SagePtr

Considering that the news is the same for all site visitors, their headlines can be tritely requested once and stored in the cache, and when news is added / changed, the cache can be reset.
This will be clearly a better optimization than doing one instead of two trivial queries.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question