Answer the question
In order to leave comments, you need to log in
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);
});
});
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question