I try to get data from two requests on two table. But I've some difficulties to get back them as I expect. I've some group andfor each group I want to get the list of all element included in this group. So I want all groups id and all items related to them.
So I execute the second query into the callback of the first into a loop to execute the query as many time as I've results from the first query. I think thant my problem come from the loop
Groupe.getGroupeAndEqs = function getGroupeAndEqs(result) {
sql.query("SELECT DISTINCT idGrp FROM groupe_equipement", function (err, res){
if (err) {
console.log("error: ", err);
result(err, null);
}
else {
for (var i = 0; i < res.length; i++){
sql.query("SELECT e.nom FROM equipement as e, groupe_equipement as g where g.idGrp=? AND e.id = g.idEq", res[i].idGrp, function(err, res2){
if(err){
console.log("error: ", err);
result(err, null);
}
else{
// result(null, res);
//I try to create an attribute with the result of the second query
res[i].equipements += res2;
//console.log(res[i]);
//resu += result(null, res);
console.log(res2);
}
});
}
result(null, res);
}
});
}
I only get the result of the first query
You can do the whole thing in a single query. That may half your total process time. Check this query.
select g.idGrp, group_concat(distinct e.nom) from equipement e
inner join groupe_equipement g
on e.id = g.idEq
group by g.idGrp
Related
I have a segment like the following:
sql.query("SELECT * FROM tasks WHERE groupId = ? AND completed = 0", res[0].groupId, (err, res) => {
if (err) {
console.log("Error selecting from TASKS: ", err);
return result(null, res);
}
console.log("tasks: ", res);
return result(null, res);
})
In this case, you can see how the results of a previous query ( res[0].groupId ) are being plugged into the statement shown here, and it works.
I want to add another query after this one which will use a similar structure, statement something like: "SELECT * FROM updates WHERE taskId = ?". In this case, I want to use ALL of the task IDs resulting from the previous statement to plug into this query. How do I do that? I envision something like res[*].taskId in my head - no idea if that works, but that should give you the idea.
i need to run a first query that i get from it a list of auctions, i need to run a second query that for each auction i get the lowest bid for this auction.
after i get the results i need to push the lowest bid to the auctions json that i recive from the first query (results1) in for loop.
when i console log results i get a array with 9 object (it should be 3) and the lowest bid property is only exists on 3 of them objects, it might be better way of doing this.
the console.log of results after adding it the lowest bids :
https://imgur.com/a/eiYcycZ
router.get('/get-live-auctions', auth, (req, res) => {
try {
const userID = req.userData.userID;
db.query(`SELECT auctions.UID,auctions.OriginCompany,auctions.DestinationCompany,auctions.OriginAddress,auctions.DestinationAddress,auctions.PickupDate,auctions.TotalWeight,auctions.StartDate,auctions.BidEndDate,auctions.AuctionEndDate,auctions.AuctionState,auctions.AuctionSerialNumber
From auctions
WHERE UserId='${userID}' AND AuctionState = 2 OR AuctionState = 3 OR AuctionState = 4`, (
err, results, fields) => {
for (let i = 0; i < results.length; i++) {
let auctionsIDS = results[i].UID;
db.query(`SELECT MIN(TotalPrice) AS lowestBid
FROM bids
Where AuctionID = '${auctionsIDS}'
`, (err2, results2, fields2) => {
let lowestBid = results2[0].lowestBid;
results.lowestBid = lowestBid;
console.log(results);
if (err2) return res.send(error);
}
)
}
res.status(200).json(results);
});
} catch (error) {
return res.status(500).send("Server error");
}
})
how to solve this issue?
I am trying to display specific data from a table in mysql using this code. I am in between using a for loop but it says that res or response is not defined. What do I need to edit or change in my code below?
function lowInventory() {
console.log("View all product that are low in inventory...\n");
for (var i = 0; i < response.length; i++) {
connection.query("SELECT stock_quantity (*) FROM products WHERE stock_quantity < 5", function (err, res) {
if (err) throw err;
//log all results of the SELECT statement
console.table(Response);
connection.end();
});
}
}
I need for it to display results of quantity that is less than 5 in node.js from my table.
change console.table(Response) to console.log(Response)
I got a function like getItemPrice in nodeJS. But while trying to inserting datas there is a error occuring. Can't write any dynamic value inside VALUES(item.Id, value.lowest_price).
I've tried lots of things bot none of work.
con.query('SELECT game_item.id as itemId, steam_app_game.app_id as gameId, game_item.name, steam_app_game.id FROM steam_app_game LEFT JOIN game_item ON steam_app_game.id = game_item.app_game_id', function(err, rows, fields) {
var counter = 1;
rows.forEach(function (item,index) {
setTimeout(function(){
market.getItemPrice(item.gameId, item.name).then(function (value, err) {
if(err) throw err;
var lowest = value.lowest_price
con.query('INSERT INTO game_item_spec(game_item_id,price) VALUES (item.itemId,value.lowest_price )')
counter ++;
});
}, index * 5000);
});
});
Here is the error.
ER_BAD_FIELD_ERROR: Unknown column 'value.lowest_price' in 'field list'
at Query.Sequence._packetToError (F:\Xamp\htdocs\steam-trade-bot\node_modules\mysql\lib\protocol\sequences\Sequence.js:47
:14)
I solved this using parameter statements in nodeJs. Single insert into doesn’t work for if the data has special chars
A query must be a string, so to inject some variables inside you can use ES6 syntax with template string.
Here the working code:
con.query('SELECT game_item.id as itemId, steam_app_game.app_id as gameId, game_item.name, steam_app_game.id FROM steam_app_game LEFT JOIN game_item ON steam_app_game.id = game_item.app_game_id', function(err, rows, fields) {
var counter = 1;
rows.forEach(function (item,index) {
setTimeout(function(){
market.getItemPrice(item.gameId, item.name).then(function (value, err) {
if(err) throw err;
var lowest = value.lowest_price
con.query(`INSERT INTO game_item_spec(game_item_id,price) VALUES (${item.itemId}, ${value.lowest_price} )`)
counter ++;
});
}, index * 5000);
});
});
I recommend that you use node async https://caolan.github.io/async/, use series together with eachOfSeries
First of all, I have to tell you I'm pretty noob in this "universe". I'm using: ExpressJs, MySql, Body-Parser, Express-session, Ejs template for creating an Basic Contacts Application in Node.
My database is composed from 3 tables:
user (user_id, first, second name, username, password)
contacts (ct_id, first, second name, phone numb.)
user_contacts (user_id, ct_id) --> foreign keys for user and contacts
I want to listing on /myProfile page all details about user and his contacts.
I don't know how to handle the select queries.
So, after some documentation I did this:
conn.query('SELECT * FROM user_contacts WHERE user_id= ?', req.session.user_id, function (err, result) {
if(err) throw err;
console.log(result);
var queryArray = "";
for(var i = 0; i < result.length; i++){
queryArray += `SELECT * FROM contacts WHERE ct_id= ${result[i].ct_id}; `;
}
console.log(queryArray);
conn.query(queryArray, function (err, result) {
if(err) throw err;
console.log(result);
res.render('myProfile/contacts', {
title: `${req.session.user_nickname}'s Contacts`,
data: result
});
});
});
But I have an error
ER_PARSE_ERROR: You have an error in your SQL syntax;
..when queryArray.length > 1
I searched and it's something about Multiple statement queries but I dont know how to solve it.
Edit 2:
I modify my code..
conn.query('SELECT * FROM user_contacts WHERE user_id= ?', req.session.user_id, function (err, result) {
if(err) throw err;
var datas = [];
for(var i = 0; i < result.length; i++){
getContacts = function(query){
conn.query(query, function (err, result) {
console.log('Creating data');
data = {
user: req.session.user_nickname,
contact:{
ct_firstName: result[0].ct_firstName,
ct_SecondName: result[0].ct_SecondName,
ct_PhoneNumber: result[0].ct_PhoneNumber
}
}
return data;
});
}
console.log('Send data to array');
datas.push(getContacts(`SELECT * FROM contacts WHERE ct_id = ${result[i].ct_id}`));
}
console.log(datas); // [ undefined, undefined ]
res.render('myProfile/contacts',{
title: `${req.session.user_nickname}'s profile`,
data: datas
})
});
But now my array contain undefined objects?? Any solution?
Maybe is something about scope?
My result:
Send data to array
Send data to array
[ undefined, undefined ]
Creating data
Creating data
I push the object to array before creating it. How is it possible?
1797,
I noticed you have several small queries grabbing the contact info for a given user. You could simplify your code by combining your queries into a single one. Often times 1 big query is more efficient (plus it's easier to maintain). I'm using a join. More info here.
const contacts = [];
const query = "
SELECT c.*
FROM user_contact uc
JOIN contact c ON uc.contact_id = c.contact_id
WHERE uc.user_id = ?
GROUP BY c.contact_id
";
conn.query(query, req.session.user_id, (err, results) => {
if (err) throw new Error(err);
// it seems that this could just be 'contacts = results' since they
// have the same structure
contacts = results.map(result => {
return {
ct_firstName: result[0].ct_firstName,
ct_SecondName: result[0].ct_SecondName,
ct_PhoneNumber: result[0].ct_PhoneNumber
};
});
res.render('myProfile/contacts',{
title: `${req.session.user_nickname}'s profile`,
data: contacts
});
});