I have this query:
SELECT * FROM accounts WHERE username = "aaa" OR email = "abc#example.com" OR mobile = "123456789"
I can find which field did match like this:
var username = req.body.username;
var email = req.body.email;
var mobile = req.body.mobile;
database.query("SELECT * FROM accounts WHERE username = ? OR email = ? OR mobile = ?",[username, email, mobile, (err, result)=>{
if (result.username == username) {...}
if (result.email == email) {...}
if (result.mobile == mobile) {...}
}
But, I'd like to know which field did match without using if multiple times (if possible). So, is that possible form within Mysql only?
You can put it in the SELECT list. You can use CONCAT_WS() to combine the list of columns into a comma-separated list. It will omit NULL values, so this will just list the matched fields.
database.query(`SELECT *,
CONCAT_WS(',',
IF(username = ?, 'username', NULL),
IF(email = ?, 'email', NULL),
IF(mobile = ?, 'mobile', NULL)) AS matched_fields
FROM accounts WHERE username = ? OR email = ? OR mobile = ?`, [username, email, mobile, username, email, mobile], (err, result) => {
var matched = result.matched_fields.split(',');
matched.each(field => {
switch(field) {
case 'username': ...; break;
case 'email': ...; break;
case 'mobile': ...; break;
});
})
Create custom column in select query and that custom column has case statement with three column(username, email, mobile) matching and print respective flag in that custom column to let it know that row comes from based on which condition.
Try Below:-
SELECT * FROM accounts WHERE (username = "aaa" OR email = "abc#example.com" OR mobile = "123456789")
Whichever field has first match then your condition become true and it will return result. If you want to match all the condition then you should use AND operator
Related
I want to simplify my mysql queries. Here is my current query where I need to include columns conditionally and so there values:
const hasPassword = false;
const myEmail = xyz#yopmail.com;
const myPassword = 123456;
query("SELECT id, name, email, status, (hasPassword ? 'password ,' : '') FROM users WHERE email=${myEmail} (hasPassword ? 'AND password=${myPassword}' : '')"
How to write simplified query similar to the below format:
query("SELECT id, name, email FROM users email=? AND password=?",[email, password]);
New to Node development.
How do you put a variable in a sql query for the VALUES part. Here is what I have. Let me know if it will work.
let email = req.body.email;
let number = req.body.number;
var sql = "INSERT INTO userdata (email, number) VALUES (email, number)";
Thanks
Also, second question. is there anyway I can check if a record already exists with the same email or number within the one sql statement.
According documentation, You should to use parametrized query like:
const email = req.body.email;
const number = req.body.number;
const sql = "INSERT INTO userdata (email, number) VALUES (?, ?)";
connection.query(sql, [ email, number ],
function (err, results) {
}
);
About second question: If you want to your table will have unique records fro each email/number pair you should to add unique index based on those fields.
My query was like:
let query = `SELECT id, name FROM students WHERE school_code = "${schoolCode}" AND name REGEXP "${text}" `;
And with params:
let params = [ schoolCode, text ];
let query = `SELECT id, name FROM students WHERE school_code = "?" AND name REGEXP "?" `
Model.dataSource.connector.query(query, params, (err, res) => {} );
And it wouldn't work
(Solution below)
I thought maybe it was the REGEXP but
The Solution Was:
to remove quotes around the question marks.
e.g., this worked:
let params = [ schoolCode, text ];
let query = `SELECT id, name FROM students WHERE school_code = ? AND name REGEXP ? `
Model.dataSource.connector.query(query, params, (err, res) => {} );
I have a lessons table that contains the following fields:
id title type language level
The user through the interface can select witch lesson he wants to open.
He will start selecting the language, then the type and finally the level.
During this process I want to query the database using a single sql statement, but of course the first query will have only the language field. I came up with this syntax but it does not work:
function queryLessonList (language, type, level){
const values = [language, type, level];
const sql = "SELECT * FROM lessons WHERE (language=?) AND (? is null OR type=?) AND (? is null OR level=?)";
return query(sql, values);
}
How can I make it work?
To reduce the complexity of checking variables and building out the query, instead you can pass the function an object to match, what you want and the columns you want returning etc (as * is not ideal).
So something like:
function queryLessonList (where = {}, columns = ['*']) {
let keys = Object.keys(where)
let values = Object.values(where)
columns = !columns.length || columns[0] === '*' ?
'*': columns.map(e => '`'+e+'`').join(',')
let sql = `
SELECT ${columns}
FROM lessons
${keys.length ? 'WHERE \`'+keys.join('` = ? AND `')+'\` = ?' : ''}
`
return query(sql, values)
}
/*
SELECT *
FROM lessons
WHERE `language` = ? AND `type` = ?
*/
queryLessonList({
language: 'en',
type: 'foo'
}, [])
/*
SELECT `id`
FROM lessons
*/
queryLessonList({}, ['id'])
/*
SELECT *
FROM lessons
*/
queryLessonList()
I have a query and I am trying to run the query. The issue i think is that i have added a condition where an item from a column from the database must equal to the computer name of the user.
Hence, I created a variable called computerName that simply retrieves the host name of the computer via NodeJs.
var os = require("os");
var computerName = os.hostname(); // Detect the computer name associated with the tablet
Below is the query
connection.query("SELECT box_id, longestDimension from box where longestDimension != '' AND LOWER(box_id) = LOWER(computerName)", function(err, rows, fields) {
computerName seems to be the problem because when the query is run with a generic name such as box45 it works.
I am getting connection error. I guess the better question is how do I include a defined variable into the query
It looks like you're trying to insert computerName directly into your SQL statement. At minimum, you'd need to write something like
connection.query("SELECT box_id, longestDimension from box where longestDimension != '' AND LOWER(box_id) = LOWER('" + computerName + "')", function(err, rows, fields) {
But you should be escaping the value of computerName. You don't know what value it might contain.
connection.query("SELECT box_id, longestDimension from box where longestDimension != '' AND LOWER(box_id) = LOWER('" + connection.escape(computerName) + "')", function(err, rows, fields) {
But a better way to do it is with ? substitution:
connection.query("SELECT box_id, longestDimension from box where longestDimension != '' AND LOWER(box_id) = LOWER(?)", computerName, function(err, rows, fields) {
Also, if the collation of the box_id column is case insensitive, which is usually the default, then you can skip the lowercasing the values.
I'd write it like this, for readability
let sql = "SELECT box_id, longestDimension FROM box WHERE longestDimension != '' AND box_id = ?";
connection.query(sql, computerName, function(err, rows, fields) {
Or if your node version supports template literals
let sql = `SELECT box_id, longestDimension
FROM box
WHERE longestDimension != ''
AND box_id = ?`;
connection.query(sql, computerName, function(err, rows, fields) {
If you have multiple variables there's two ways to do it: with an object, or with an array.
Object method:
let payload = {
box_id: "Johannesburg",
longestDimension: 12.4
};
let sql = 'INSERT INTO box SET ?';
connection.query(sql, payload, function(err, rows, fields) {
});
Array method:
let computerName = "Johannesburg";
let longestDimension = 12.4;
let sql = 'INSERT INTO box SET box_id = ?, longestDimension = ?';
// alternative, equivalent SQL statement:
// let sql = 'INSERT INTO box (box_id, longestDimension) VALUES (?, ?)';
connection.query(sql, [ computerName, longestDimension ], function(err, rows, fields) {
});
You can even combine them
let payload = {
box_id: "Johannesburg",
longestDimension: 12.4
};
let boxName = "Box A";
let sql = 'UPDATE box SET ? WHERE box_name = ?';
connection.query(sql, [ payload, boxName ], function(err, rows, fields) {
});
In this last example, the payload object is substituted for the first ? and the boxName variable is substituted for the second ?.