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);
});
});
};
Related
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?
I have a mysql Query:-
SELECT #a:=#a+1 serial_number,rule FROM pledges,(SELECT #a:= 0) AS a;
This gives me a serial number along with the rule from the table.
How can I do that in Sequelize?
This is the query I wrote in the model which gives me id and rule:-
Pledge.getPledgeList = function(lang_code='EN') {
return this.findAll({
attributes:['id','rule'],
where: {
status:'a',
deleted_at:null
},
include:[
{ association: 'local', where: {lang_code:lang_code} ,required: false},
]
})
}
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"});
});
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)
});
I'm making a pretty simple RIGHT JOIN query, but I can't format the output correctly.
Here is the Query:
connection.query({sql : "SELECT users.*, rides.* FROM users RIGHT JOIN rides ON users.id = rides.id_user WHERE users.id = ?", nestTables: '_', values : [id] }, function(err, rows){
console.log(rows);
});
This is the output I have:
[ { users_id: 52,
users_firstname: 'greg', //End first table data
rides_latitude: '50.847454', //Second table data: row 1
rides_longitude: '4.358356',
},
{ users_id: 52,
users_firstname: 'greg', //Exactly the same first table data
rides_latitude: '50.9', //Second table data: row 2
rides_longitude: '4.4',
} ]
And this is the ouput I would like to have:
[ { users_id: 52,
users_firstname: 'greg',
rides : [
{
rides_latitude: '50.847454',
rides_longitude: '4.358356'
},
{
rides_latitude: '50.9',
rides_longitude: '4.4'
}
]
}]
I tried nestTables as you can see,
Wrapped for legibility:
connection.query({
sql : "SELECT \
users.users_id, \
users.users_firstname, \
rides.rides_latitude, \
rides.rides_longitude \
FROM \
users \
RIGHT JOIN rides ON users.id = rides.id_user \
WHERE \
users.id = ?",
nestTables: '_',
values : [id]
}, function (err, rows) {
var result = [], index = {};
if (err) throw err;
rows.forEach(function (row) {
if ( !(row.users_id in index) ) {
index[row.users_id] = {
users_id: row.users_id,
users_firstname: row.users_firstname,
rides: []
};
result.push(index[row.users_id]);
}
index[row.users_id].rides.push({
rides_latitude: row.rides_latitude,
rides_longitude: row.rides_longitude
});
});
console.log(result);
});