Nodejs Subselect in sql select - javascript

Ola!
I'm doing a node.js application. I have this table structure in my MySql DB:
My task is to get the table_4 names and the related table_7 names. I know the Table_1 username and password. Is it possible to create one query - using subselect - not calling all the time callback with a new select after getting values? - like below -
con.connect(function(err) {
if (err)
{throw err }
con.query("SELECT id FROM Table_1 WHERE username = xyz AND password = aaa",
function (err, result) {
if (err) {throw err};
con.query("SELECT table_3_id FROM table2 WHERE Table_1_id = "+(result)+")",
function(/*bla-bla*/){
};
});
}
);
Thanks!

Here it is how you can achieve that with one query :
SELECT Table_4.*
FROM Table_1 , Table_2 , Table_3 , Table_4
WHERE Table_1.username and Table_1.password and
Table_2.Table_1_id = Table_1.id and
Table_2.Table_3_id = Table_3.id and
Table_3.Table_4_id = Table_4.id
I couldn't found proper relations for Table_7 names. But I think you will get idea how to do it further from this.

I just talked to my lead dev, hwho gave me a correct solution - similar to #Vivek Doshi answer - :
SELECT Table_4.names, Table_7.names
FROM Table_1 , Table_2 , Table_3 , Table_4, Table_5, Table_6, Table_7
WHERE Table_1.username and Table_1.password and
Table_2.Table_1_id = Table_1.id and
Table_2.Table_3_id = Table_3.id and
Table_3.Table_4_id = table_4.id and
Table_3.table_5_id = table_5.id and
table_6.table_5_id = Table_5.id and
table_6.table_7_id = table_7.id;

Related

select query in MySQL NodeJS

I am making search route for property table where user can enter city, state, street_address , minamount , max_amount to search for different properties. My problem is if user only enter one or two fileds search should be filter by those field only. and if user does not enter any parameters, it should show every property.
const sqlQuery = `SELECT * FROM property WHERE state = ? AND city = ? AND street_address = ? AND min_amount >= ? AND max_amount <= ?; `
const values = [req.body.state, req.body.city, req.body.street_address ,req.body.min_amount,req.body.max_amount];
let data = [];
db.query (sqlQuery, values, function (err, results, fields) {
if (err) {
console.log(err)
}
if (results.length >= 1) {
}
You need to construct your sqlQuery manually by checking the existence of each parameter and appending a corresponding WHERE clause individually for each parameter, if this parameter exists.

MySql query to get all user's conversations and data about user that he is having conversation with

db structure
I am creating simple conversation app. I have three tables - users(id,name), conversations(id,user1_id, user2_id) and messages (id,conversationId,sender,message,date). Is there a way to actually get all user's conversations and data about another user in one query?
The query below gets id's of the user that logged user has conversations with. I would like now to get these users data base on their id. Thanks for all suggestions.
const getChats = (req, res) => {
const userId = req.params.userId;
db.query(
"SELECT DISTINCT CASE WHEN user1_id = ? THEN user2_id ELSE user1_id END userID FROM conversations WHERE ? IN (user2_id , user1_id)",
[userId, userId],
(e, r) => {
res.send(r);
}
);
};
module.exports = { getChats };
First, I'll answer the second question "how can get rid of doubling conversations where only conversation id differs and users are basically swapped?" to resolve this issue you need to check the conversation table before insertion by the below query
db.query(
"SELECT * FROM conversations WHERE (user1_id = ? AND user2_id = ?) OR (user1_id = ? AND user2_id = ?)",
[senderId, receiverId,receiverId,senderId],
(e, r) => {
res.send(r);
}
);
if the above query returns a record then we'll not insert a new row.
now query for message with user data of a conversation
db.query(
"SELECT m.*,c.id,
s.name as "SenderUserName",
r.name as "ReceiverUserName",
FROM messages m
inner join conversations c on m.conversationId = c.id
inner join user r on r.id = c.user1_id
inner join user s on s.id = c.user2_id
WHERE (c.user1_id = ? AND c.user2_id = ?) OR (c.user1_id = ? AND
c.user2_id = ?)",
[senderId, receiverId,receiverId,senderId],
(e, r) => {
res.send(r);
}
);
the above query will return all messages between 2 users.
though you can remove the conservations table from the structure and it will be easy approach, here is the structure that i suggest
users table
name
type
id
int
name
varchar
messages table
name
type
id
int
message
text
sender_id
int
receiver_id
int
created_at
timestamp

node js sql output

I am trying to come up with the node.js code to get the output of this query:
const viewAllEmployees = () => {
let sql = 'SELECT e.id, e.first_name, e.Last_name, r.title, d.name as "Department", salary, CONCAT (m.first_name," ", m.last_name) AS "Manager"
FROM employee e ' + connection.escape('INNER JOIN employee m
ON e.manager_id = m.id
LEFT JOIN role r
ON e.role_id = r.id
LEFT JOIN department d
on r.department_id = d.id');
connection.query(sql, (err, res) => {
if (err) throw err;
console.table(res);
// console.log(res);
//connection.end();
});
The problem is that when I use it without the connection.escape(), I get the output, but with single quotes like this:
How can I (1) get rid of the (index) column, and (2) get rid of the single quotes?
Getting rid of the single quotes is really the priority.
Thanks!
Index column and quotes are added by console.table function itself.
You can check it running console.table with any static data like here:
https://developer.mozilla.org/en-US/docs/Web/API/Console/table#collections_of_primitive_types
To print it in a way you want it, implement printing function on your own.

How to find "By Name" in mongoose

I am trying to get database values using a specific name. I want to get all the books an author written.
This is my code to get the first name of the author and search for all the books he's written in BookDB using Like operator as in mysql
//get books by author name
router.route('/authorName').get((req, res) => {
let authorName = req.params.authorName; //how can i pass this value to below regex command
BookDB.find({"firstName": /authorName/}, (err, books) => {
if(err) throw err;
res.status(200).send(books);
});
});
Problem: How can I pass authorName to the {"firstName": /authorName/}.
The way I have written, it is not set the authorName properly.
I am not sure in the mongoose part, but you can also create regular expressions as:
new RegExp(exp: string, flags: string)
Note if you use this format, the start and end slash has no special meaning, they would mean the string starts with a slash
I did some research and found $regex.
//get books by author name
router.route('/authorName').get((req, res) => {
let authorName = req.params.authorName;
BookDB.find({firstName: {$regex: `${authorName}`}}, (err, books) => {
if(err) throw err;
res.status(200).send(books);
});
});
This will find all the results that containing this particular string authorName in BookDB database

How to insert json data into MariaDB using Nodejs?

I'm inserting JSON data into MariaDB using NodeJs. Getting below error while inserting data. Please advise what cause to get error. Actually Column data1 no empty or null values.Why am i getting below error ?
{ [Error: Column 'data1' cannot be null] code: 1048 }
Table Structure
CREATE TABLE `from_excel` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`data1` VARCHAR(50) NULL DEFAULT NULL,
`data2` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`ID`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
;
Code which i'm using to insert data.
var Client = require('mariasql');
var c = new Client({
host : 'localhost',
user : 'xxxx',
password : 'xxxx',
db : 'Metrics'
});
const workbook = xlsx.readFile(__dirname + '/test.xlsx');
const worksheet = workbook.Sheets[workbook.SheetNames[0]];
var json=xlsx.utils.sheet_to_json(worksheet);
console.log(json.length);
for(var i=0;i<json.length;i++)
{
var post = {data1: json[i].data1, data2: json[i].data2};
var sql = c.query('INSERT INTO elements_from_excel (data1,data2) VALUES (?,?)', post, function(err, result) {
console.log(sql);
if(err){console.log(err);}
else {console.log("success");}
});
}
c.end();
What could be happening is that the resulting insert statement being run is as follows:
INSERT into from_excel (data1, data2) VALUES (`data1` = \'data1value\', `data2` = \'value\', ?)
Try replacing the query string with the following instead:
var post = {data1: json[i].data1, data2: json[i].data2};
var sql = c.query('INSERT INTO from_excel SET ?', post, function(err, result) {
console.log(sql);
if(err){console.log(err);}
else {console.log("success");}
It should be INSERT INTO from_excel VALUES (?), although it's quite possible that you'll encounter other errors when you fix this one.
Make sure the function you are calling receive the exact type of data they expect.

Categories

Resources