I try to make a Daily Gamble Game however - mysql

I try to get the Highest Number out of my Databse.
So far so good Test 1 Code:
const db = require("../../../database.js")
const test = require("./test.js")
module.exports = {
config: {
name: "try",
description: "Replies with a Number.",
},
permissions: ['SendMessages'],
owner: false,
run: async (client, message, args, prefix) => {
const test = await db.query("select Number, MemberID from numbers order by Number DESC LIMIT 3;")
console.log(test[1])
console.log(test[1].Number)
}}
But all I get out in my Console is:
Executing (default): select Number, MemberID from numbers order by Number DESC LIMIT 3;
[ { Number: 138, MemberID: '318735407963439104' } ]
undefined
So I tried another Version:
const db = require("../../../database.js")
module.exports = {
config: {
name: "stats",
description: "Replies with a Number.",
},
permissions: ['SendMessages'],
owner: false,
run: async (client, message, args, prefix) => {
const query = await db.query("select Number, MemberID from numbers order by Number DESC LIMIT 3;", async function (err, result, fields)
{
console.log(query)
const level = result[0].Number
const user = result[0].MemberID
const level1 = result[1].Number
const user1 = result[1].MemberID
const level2 = result[2].Number1
const user2 = result[2].MemberID
console.log(level)
})
}
};
But this just showed this in the Console
Executing (default): select Number,MemberID from numbers order by Number DESC LIMIT 3;
and nothing else.
I'm really depressed that nothing works, can someone help?

Related

accessing mysql columns as arrays

i have two tables one for posts and another one for comments ,
posts table
post_id
text
1
row1
2
row2
3
row3
comments
post_id
Another header
user id
1
comment
2
1
comment 2
3
i want to read the code as follows:
post:{
id:1,
comments:[{text:"My comment",userId:3},
}
const db = require('mysql2'); // async/await works only in mysql2
// I am supposing your comments table has post_id, another_header and user_id columns
app.get('/comments', async (req, res) => {
const comments = await db.query('Select * from comments');
let arrayOfObjects = [];
comments.forEach(elem => {
arrayOfObjects.push({
id: elem.post_id,
comments: elem.another_header,
user_id: elem.user_id
});
})
console.log(arrayOfObjects);
});

Get `Sum of` from two different join(Includes) in Sequelize

I want to get sum of column from two different tables in sequilize.
I want to accurate totalpaid, refunded & refundable field, which vary according to group by, I'm not be able to resolve it.
//Some pre-desined variables
var totalPaidQueryStr = '(CASE WHEN (SUM(inv_payment_record_invoices.payment)) IS NULL THEN 0 ELSE (SUM(inv_payment_record_invoices.payment)) END)';
var totalPaidQuery = [Sequelize.literal(totalPaidQueryStr), 'totalpaid']; //Get the total paid amount till date;
var refundedQueryStr = '(CASE WHEN (SUM(inv_payment_record_refunds.amount)) IS NULL THEN 0 ELSE (SUM(inv_payment_record_refunds.amount)) END)';
var refundedQuery = [Sequelize.literal(refundedQueryStr), 'refunded']; //Get the total paid amount till date
var refundableQueryStr = `(inv_payment_records.amount - (${totalPaidQueryStr} + ${refundedQueryStr}))`;
var refundableQuery = [Sequelize.literal(refundableQueryStr), 'refundable']; //Get the total due amount
return InvPaymentRecords.findOne({
attributes: [
'customer_id',
'amount',
'company_currency_id',
'exchange_rate',
totalPaidQuery, //Want to accurate sum
refundedQuery, //Want to accurate sum
refundableQuery
],
where: {
'id': payment_record_id,
'company_id': company_id
},
include: [
{
model: InvPaymentRecordInvoices,
require: false,
attributes: [],
},
{
model: InvPaymentRecordRefund,
require: false,
attributes: [],
}
],
group: [
//'inv_payment_records.id',
//'inv_payment_record_invoices.id',
//'inv_payment_record_refunds.id'
]
}).then(iprdata => {
return sequelize.Promise.resolve(iprdata);
}).catch(error => {
return sequelize.Promise.reject(error);
})

How to write subquery with multiple where in sequelize using NodeJS

I need to execute this query using sequelize.
select * from mysqlDB.songTable where
X in (SELECT X FROM movieDB4.songTable where Y like('%pencil%') and Z='title') and
Y='tam' and Z='language';
I tried like this. but it throws some invalid value[object] error. please help to resolve this query.
const tempSQL = sequelize.dialect.QueryGenerator.selectQuery('songTable',{
attributes: ['X'],
where: {
Y: {$like: '%'+text[i]},
Z: "content_title"
}})
.slice(0,-1); // to remove the ';' from the end of the SQL
User.findAll({
where: {
X: {
$in: sequelize.literal('(' + tempSQL + ')'),
$and: {Y: lang.substring(0,3),
Z: 'language'}
}
}
})
You can use sequelize.query() to execute raw queries.
Example
return this.sequelize.query(`SELECT category_id, category_name from table_categories where category_id in (SELECT DISTINCT category_id from table_authorized_service_center_details where center_id in (SELECT center_id from table_authorized_service_center where brand_id ${condition}));`).then((results) => {
if (results.length === 0) {
reply({status: true, categories: [], forceUpdate: request.pre.forceUpdate});
} else {
reply({status: true, categories: results[0], forceUpdate: request.pre.forceUpdate});
}
}).catch((err) => {
console.log(err);
reply({status: false, message: "ISE"});
});

Get row count before LIMIT but on it's own row

I'm trying to get the full row count before i limit the return in postgres, which I have using:
count(*) OVER() AS full_count
However as I put it in the select it outputs it with every row which is less then ideal. I'm outputting it in NodeJS as JSON and noticed that the output contains it's own tow with rowCount, but this is after the limit, is there a way to replace the rowCount in the JSON with full_count, or a better way of trying to do what I'm doing? This is my query thus far:
SELECT name, id, count(*) OVER() AS full_count FROM table ORDER BY id ASC LIMIT ($1) OFFSET ($2)
Update
Expected output:
{
total : 170000
rows : [
{
name : Karl,
age : 31,
},
name : Helen,
age : 36
}
]
}
Update 2
NodeJS
Route
router.get('/api/v1/person/:limit?/:offset?', (req, res, next) => {
person.get(req, res);
});
Model
this.get = function(req, res) {
var limit = req.params.person_limit || 10;
var offset = req.params.person_offset || 0;
if (limit > 100) {
limit = 100;
}
pool.connect(function(err, client, done) {
if(err) {
done();
console.log(err);
return res.status(500).json({success: false, data: err});
}
client.query('SELECT name, id FROM person ORDER BY id ASC LIMIT ($1) OFFSET ($2)',[limit, offset], function(err, result) {
done();
if(err) {
return console.error('error running query', err);
}
res.send(result);
});
});
};

running a query on each iteration

Can somebody help me with this query on a returned query?
I want the query to iterate through the results of the previous query to see if a voucher has been used
this is the code for the query :
db.query('SELECT * FROM Table WHERE ID in ?', [(1,2,3,4)],
function(err, rows) {
if (err) throw err
var items = []
rows.forEach(function(i) {
var item = {
'item1': i.item1,
'item2': i.item2,
'item3': i.item3
}
db.query('SELECT * FROM Table2 WHERE ID = ?', [i.ID],
function(err, rows2) {
if (err) throw err
item.subvalue = rows2
})
items.push(item)
})
res.json(items)
})
So I did this in the end. used multiple statement where the second query returns all possible results need for results in query 1. Then I can iterate through results 1 and results 2 within it.
Still not sure this is the best approach but it works. Any suggestions are very welcome
db.query('SELECT 1 WHERE Range ?; SELECT 2 WHERE ID IN (SELECT 1)',
[req.body.hotelid, '2015-11-01', '2015-11-30',
req.body.hotelid, '2015-11-01', '2015-11-30'],
function(err, result) {
if (err) console.log(err)
else
var items = []
result[0].forEach(function(i) {
var giftVoucherUsed = []
var item = {
'ID': i.BookingID,
'BookingDate': i.BookingDate,
'GuestName': 'Guestname'
}
result[1].forEach(function(g){
if(g.BookingID == i.BookingID){
giftVoucherUsed.push(g)
}
})
item['GiftVoucher'] = giftVoucherUsed
items.push(item)
})
res.json(items)
});