How to write mysql subquery in Knex? - mysql

I am trying to write mysql subquery sql in knex but the results of query are undesired.
This is my MySQL query:
select *
from istifta
where istifta_id not in (
select istifta_id
from status
where status = 'divided'
)
This is my query converted to Knex:
subquery = await ctx.knex
.select('istifta_id')
.from('status')
.where('status', 'divided')
result = await ctx.knex
.select()
.from('istifta')
.where('istifta_id', 'not in', subquery)
MySQL query is returning two rows all of which doesn't have status = 'divided'
While Knex is returning three rows with a row having status = 'divided'

You can use .whereNotIn together with the function() definition option to nest your subquery. Your subquery is inside of the function() as:
select('istifta_id').from('status').where('status', 'divided')
and the .on functions just make debugging a bit easier.
result = await ctx.knex.from('istifta')
.whereNotIn( 'istifta_id', function() {
this.select('istifta_id').from('status').where('status', 'divided')
})
.on('query', function(data) {
console.log("TEST001 data:", data); })
.on('query-error', function(ex, obj) {
console.error("TEST002 KNEX query-error ex:", ex, "obj:", obj);
})

Related

MySQL query for filtering

I want to write a query in MySQL for filtering. For example, if there is a column id in table table1 where the filter values for id come in a POST request body, saved in variable A. I want to extract the matching rows if A is not empty and return all rows otherwise. I am not sure about using IN with WHERE.
SELECT * FROM table1 WHERE id IN (A)
One option is that I return all rows from the database and use JavaScript filters, but I don't want to return all rows and expose the entire table to user.
NOTE: A can be a single value, a tuple or an array.
If you use javascript, use A.join(), and sanitize your POST.
var your_post = [1, 2, 3];
var A = your_post.join();
if (A == '') {
var sql = 'SELECT * FROM table1';
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
} else {
var sql = 'SELECT * FROM table1 WHERE id IN (?)';
con.query(sql, [A], function (err, result) {
if (err) throw err;
console.log(result);
});
}

Check IF Result from Select Query with Async NodejS in MySQL?

I've got the following code in NodeJS using an Async/Promises wrapper for Mysql ;
row_c = await db.query( 'SELECT tagid FROM tags WHERE tagname = ?', [tag1] );
How do I now check if there is a result for an IF statement?
I tried;
if (row_c.tagid){
///some code
}
But it's not picking up the conditional. How do I check if the query returned a row?
db.query returns an array of rows. You can do the following:
row_c = await db.query( 'SELECT tagid FROM tags WHERE tagname = ?', [tag1] );
if (row_c.length) {
// if data is returned
console.log(row_c);
}

Node.js - getting a value from MySQL and assigning it to a variable

My query:
pool.query("SELECT MAX(ID) FROM `games` WHERE status IN('0','1') LIMIT 1", (err, row) => {
if(err) return console.log("err getting the game.");
currentGame = row[0];
console.log(currentGame);
});
Current Result:
RowDataPacket { 'MAX(ID)': 1 }
Desired Result:
1
How do I get just the value and not include the other stuff?
Try adding an alias to your count query, and then access it:
pool.query("SELECT MAX(ID) AS max_id FROM games WHERE status IN ('0','1')", (err, row) => {
if(err) return console.log("err getting the game.");
currentGame = row[0].max_id;
console.log(currentGame);
});
Note: A max query by definition will always return only a single record result set (in the absence of GROUP BY), so there is no need for LIMIT 1.

Query in Mysql and Node.js

I have this Mysql query that is working fine. However, I need to add 2 more conditions and I'm not sure how to do this.
//index.js
module.exports = {
getHomePage: (req, res) => {
let query ='SELECT Tbl_Email_mensagens.codigo AS Codigo, Tbl_Email_mensagens.mensagem AS Mensagem,Tbl_Email_mensagens.celular AS Celular, cm_custmaster.fullname AS NomeCompleto FROM Tbl_Email_mensagens LEFT JOIN cm_custmaster ON Tbl_Email_mensagens.celular = cm_custmaster.mobile';
// execute query
db.query(query, (err, result) => {
if (err) {
res.redirect('/');
}
res.render('index.ejs', {
title: ""
,players: result
});
});
},
};
I then need to add these 2 conditions:
Where group = '7' and send = '0'
Very thanks!
SELECT Tbl_Email_mensagens.codigo AS Codigo,
Tbl_Email_mensagens.mensagem AS Mensagem,
Tbl_Email_mensagens.celular AS Celular,
cm_custmaster.fullname AS NomeCompleto
FROM Tbl_Email_mensagens
LEFT JOIN cm_custmaster ON Tbl_Email_mensagens.celular = cm_custmaster.mobile
WHERE Tbl_Email_mensagens.`group` = 7
AND Tbl_Email_mensagens.send = 0
Pay attention - the word group is reserved one, so it MUST be wrapped into backticks. But it is more safe to rename it, to some group_number, for example.
Whereas the quotes over the values are excess (you may store them if according field has any string datatype).

Linq-to-sql - query is not filtered

I am really new to Linq and am using Linq-to-Sql as follows. However in the following example, my where clause never gets executed and the resultant query attempts to fetch all the records from my table, ignoring even the take method.
Can somebody point out as to what i am doing wrong
var baseQry = db.Table;
baseQry.Where(a => a.tab_id == theId);
baseQry.Select(o => new
{
o.name,
o.display_name,
o.type,
o.info,
time_stamp = (Convert.ToDateTime(o.timestamp).ToLongDateString())
}).Take(10);
baseQry.ToList();
Your second line...
baseQry.Where(a => a.tab_id == theId);
...is essentially a no-op, because the resulting query isn't carried over into your .Select clause.
You need to change it to this:
var baseQry = db.Table;
var results = baseQry
.Where(a => a.tab_id == theId)
.Select(o => new
{
o.name,
o.display_name,
o.type,
o.info,
time_stamp = (Convert.ToDateTime(o.timestamp).ToLongDateString())
})
.Take(10)
.ToList();