MySql Store Procedure Search Like - mysql

I have search field with param called "query" this param will search different columns for a match. It works but the query has to match exactly in order to get a return. I have tried using '%' but I dont think I am using it correctly. Im trying to have more generatic search.
CREATE DEFINER=`root`#`localhost` PROCEDURE `client_search_reps`(IN offset INT, IN row_count INT, IN query varchar(100))
BEGIN
SELECT
U.Id,
U.RoleId,
UP.FirstName,
UP.LastName,
UP.FileUrl,
L.City,
L.Zip,
CP.Name,
CP.Url,
CP.Phone,
CP.Email,
P.ProductOne,
P.ProductTwo,
P.ProductThree,
P.ProductFour,
FROM user_profiles AS UP
LEFT JOIN users AS U ON U.Id = UP.UserId
LEFT JOIN location AS L ON L.UserProfileId = UP.UserId
LEFT JOIN company_profile AS CP ON CP.UserId = UP.UserId
LEFT JOIN products AS P ON P.UserId = U.Id
WHERE UP.FirstName LIKE query || UP.LastName LIKE query || CP.Name LIKE query
|| CP.Phone LIKE query || CP.Email LIKE query
LIMIT offset, row_count;
END
Below is my React.Js code just in case it helps understand my issue.
searchAccount = (query) => {
profileServices
.searchAccounts(0, query)
.then(this.searchSuccess)
.catch(this.searchError);
};
searchSuccess = (data) => {
let accounts = data.item.pagedItems;
this.setState({
mappedProfiles: accounts.map(this.mapSearch),
currentItems: data.item.totalCount,
});
};
searchError = (data) => {
swal({
title: "Search is Broad",
text: "Search by: Company Name, Phone, or Email",
icon: "warning",
buttons: true,
dangerMode: true,
});
};
onSearch = (e) => {
let value = e.target.value;
this.setState((prevState) => {
return {
...prevState,
query: value,
};
});
};
clearSearch = () => {
this.setState((prevState) => {
return {
...prevState,
query: "",
};
});
// this.getProfiles(0);
};
search = () => {
if (this.state.query.length > 0 ? this.searchAccount(this.state.query) : 0);
this.setState({
searchModal: true,
});
};

You can add SQL's wildcard character to the query
CREATE PROCEDURE client_search_reps(
offset INT,
row_count INT,
query varchar(100)
)
BEGIN
SET query = CONCAT('%', query, '%');
...
Btw, it's better to use standard OR instead of non-standard || (the || is deprecated in MySQL 8.0.17 and has different behavior depending on the sql_mode being used in all versions).

Related

node.js mysql query update from an array

i am beginner in node.js , i hava an array of json data and i wanted to update my table squad by all the rows of my json array , so i used a loop , and then after i execute , i can only see the json input with console.log(data.players) but there is no response or anything , like the function is dead , no errors , the update is not done , just displaying the entry data
Here the input data:
{"id":1,"email":"d","password":"d","name":"d","price":5,"points":5,"fixture":"d","userid":1,
"players":
[{"id":2724,"firstname":"Lucas Digne","lastname":"Lucas Digne","position":"D","price":0,"rating":"7.3","appearences":1,"goals":0,"assists":0,"cleansheets":0,"redcards":0,"yellowcards":0,"image":"https://media.api-sports.io/football/players/2724.png","teamid":45,"clubid":1,"fixtureid":592848,"points":2},{"id":19599,"firstname":"Emiliano Martínez","lastname":"Emiliano Martínez","position":"G","price":0,"rating":"6.6","appearences":1,"goals":0,"assists":0,"cleansheets":5,"redcards":0,"yellowcards":0,"image":"https://media.api-sports.io/football/players/19599.png","teamid":66,"clubid":1,"fixtureid":592855,"points":11},{"id":2741,"firstname":"Mathew Ryan","lastname":"Mathew Ryan","position":"G","price":0,"rating":"5.0","appearences":1,"goals":0,"assists":0,"cleansheets":0,"redcards":0,"yellowcards":0,"image":"https://media.api-sports.io/football/players/2741.png","teamid":42,"clubid":1,"fixtureid":592851,"points":-1},{"id":289,"firstname":"Andrew Robertson","lastname":"Andrew Robertson","position":"D","price":0,"rating":"7","appearences":1,"goals":0,"assists":0,"cleansheets":0,"redcards":0,"yellowcards":0,"image":"https://media.api-sports.io/football/players/289.png","teamid":40,"clubid":1,"fixtureid":592850,"points":2},{"id":289,"firstname":"Andrew Robertson","lastname":"Andrew Robertson","position":"D","price":0,"rating":"7","appearences":1,"goals":0,"assists":0,"cleansheets":0,"redcards":0,"yellowcards":0,"image":"https://media.api-sports.io/football/players/289.png","teamid":40,"clubid":1,"fixtureid":592850,"points":2},{"id":2726,"firstname":"Kurt Zouma","lastname":"Kurt Zouma","position":"D","price":0,"rating":"7.2","appearences":1,"goals":0,"assists":0,"cleansheets":0,"redcards":0,"yellowcards":0,"image":"https://media.api-sports.io/football/players/2726.png","teamid":49,"clubid":1,"fixtureid":592851,"points":2},{"id":633,"firstname":"İlkay Gündoğan","lastname":"İlkay Gündoğan","position":"M","price":0,"rating":"8.3","appearences":1,"goals":0,"assists":1,"cleansheets":0,"redcards":0,"yellowcards":0,"image":"https://media.api-sports.io/football/players/633.png","teamid":50,"clubid":1,"fixtureid":592852,"points":5},{"id":633,"firstname":"İlkay Gündoğan","lastname":"İlkay Gündoğan","position":"M","price":0,"rating":"8.3","appearences":1,"goals":0,"assists":1,"cleansheets":0,"redcards":0,"yellowcards":0,"image":"https://media.api-sports.io/football/players/633.png","teamid":50,"clubid":1,"fixtureid":592852,"points":5}]}
Here the node.js:
updatefixture:(data,callback)=>{
console.log(JSON.stringify(data));
for(var item of data.players){
pool.query(
'UPDATE squad SET appearences = 1, rating = ? goals = ? assists = ? , cleensheets = ?, redcards = ?, yellowcards = ? , points = ? WHERE id = ? AND fixtureid = ? ',
[
item.id,
item.rating,
item.goals,
item.assists,
item.cleansheets,
item.redcards,
item.yellowcards,
item.points,
item.id,
item.fixtureid
],
);
}
(error,result) => {
if(error){
console.log(error);
return callback(error);
}
return callback(null,result);
}
},
I just want a way to update all rows with the condition that made with where clause and make sure that the rows will be updated, any help for a beginner like me will be so appreciated
It seems you just moved callback of pool.query function outside of the loop.
Try the following:
updatefixture:(data,callback)=>{
function addPlayer(item) {
return new Promise((accept, reject) => {
pool.query('UPDATE squad SET appearences = 1, rating = ? goals = ? assists = ? , cleensheets = ?, redcards = ?, yellowcards = ? , points = ? WHERE id = ? AND fixtureid = ? ',
[
item.id,
item.rating,
item.goals,
item.assists,
item.cleansheets,
item.redcards,
item.yellowcards,
item.points,
item.id,
item.fixtureid
], (error, result) => {
if(error){
reject(error);
} else {
accept(result);
}
});
});
}
console.log(JSON.stringify(data));
Promise.all(data.players.map(addPlayer)).then((result)=>{
console.log(result)
callback(null, result)
}).catch((error)=>{
console.log('Error:', error)
callback(error)
})
},

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).

Mysql, Node, query within a query, how to populate property in map function from another query

Firstly, if anyone can edit my question title or question to make more sense, please do.
I have a node/express app making mysql queries with mysql.js. I have a query that looks up a table of questions and then runs a map function on the results. Within that map function, I need to query another table, of answers, corresponding to each record in the questions table. The value I need is the number of answers to that question, ie the number of records in each answers table. I've tried all kinds of different examples, but nothing quite fits my case in a way that makes sense to me. New at Node and Express, and even MySQL so having a hard time picking out quite what to.
I understand that the problem is the async nature of node. getAnswersCount() returns "count" before the query finishes. Below is my code. Need some advice on how to achieve this.
The value 123 is assigned to count just to clarify the trace results.
app.get('/', (req, res) => {
db.query('SELECT * FROM questions LIMIT 0, 100',
(error, results) => {
if (error) throw error;
questions = results.map(q => ({
id: q.id,
title: q.title,
description: q.description,
answers: getAnswersCount( q.id )
}));
res.send( questions );
});
});
const getAnswersCount = ( id ) =>
{
const tableName = 'answers_' + id;
var count = 123;
var sql = `CREATE TABLE IF NOT EXISTS ${tableName}(
id int primary key not null,
answer varchar(250) not null
)`;
db.query( sql,
(error, results) => {
if (error) throw error;
//console.log( 'answers table created!' );
});
sql = `SELECT COUNT(*) AS answersCount FROM ${tableName}`;
db.query( sql,
(error, results) => {
if (error) throw error;
//console.log( count ); // will=123
count = results[0].answersCount;
//console.log( count ); // will = results[0].answerCount
});
// I know this code runs before the query finishes, so what to do?
//console.log( count ); //still 123 instead of results[0].answersCount
return count;
}
EDIT: After attempting various versions of Michael Platt's suggestion in his answer without success, I finally worked out a solution using Express callbacks and a promise, adding the answers values to the questions array afterwards:
app.get( '/', (req, res, next ) => {
db.query('SELECT * FROM questions LIMIT 0, 100',
(error, results) => {
if (error) throw error;
questions = results.map(q => ({
id: q.id,
title: q.title,
description: q.description,
}));
next();
});
}, (req, res ) => {
questions.map( currentElem => {
getAnswersCount( currentElem.id ).then( rowData => {
currentElem.answers = rowData[0].answersCount;
if( currentElem.id == questions.length ) res.send( questions );
});
});
});
const getAnswersCount = ( id ) => {
const tableName = 'answers_' + id;
var sql = `CREATE TABLE IF NOT EXISTS ${tableName}(
id int primary key not null,
answer varchar(250) not null
)`;
db.query( sql,
(error, results) => {
if (error) throw error;
//console.log( 'answers table created!' );
});
sql = `SELECT COUNT(*) AS answersCount FROM ${tableName}`;
return new Promise( ( resolve, reject ) => {
db.query( sql, ( error, results ) => {
if ( error ) return reject( err );
resolve( results );
});
});
}
I'm not sure which database module you are using to connect to and query the database but you could make the method async and then await the response from the query like so:
const getAnswersCount = async ( id ) =>
{
const tableName = 'answers_' + id;
var count = 123;
var sql = `CREATE TABLE IF NOT EXISTS ${tableName}(
id int primary key not null,
answer varchar(250) not null
)`;
var results = await db.query(sql);
sql = `SELECT COUNT(*) AS answersCount FROM ${tableName}`;
var count = db.query(sql)[0].answerCount;
// I know this code runs before the query finishes, so what to do?
//console.log( count ); //still 123 instead of results[0].answersCount
return count;
}
app.get('/', async (req, res) => {
db.query('SELECT * FROM questions LIMIT 0, 100',
(error, results) => {
if (error) throw error;
questions = results.map(q => {
const answerCount = await getAnswersCount( q.id )
return {
id: q.id,
title: q.title,
description: q.description,
answers: answerCount
}
}));
res.send( questions );
});
});
I think that will give you what you want and run correctly but it might require a bit of tweaking. You may need to async the function on the actual route itself as well and await the call for getAnswersCount but that should just about do it.

rewrite left outer join for sub queries in bookshelf.js

Note : I have not shared database schema as I am mainly looking for a help only w.r.t. last step which is 'left outer join' on 2 sub-queries.
select *
from
(select id
from Action
where id = 3) AS act1
left Outer Join
(select Action.name,
completed_At as completedAt,
deadline, notes,
ActionAssignedTo.action_Id as actionId,
from Action
inner join Employee
on Action.created_By_Id = Employee.id
and Employee.vendor_Id = 2
inner join ActionAssignedTo
on Action.id = ActionAssignedTo.action_Id
and ActionAssignedTo.action_Id = 3
where Action.created_By_Id = 7
group by Action.id
limit 2) AS act2
on act1.id = act2.actionId
I need to write this above query using Bookshelf
let options = {columns: [ 'Action.name', 'completed_At as completedAt',
'deadline', 'notes',
'ActionAssignedTo.action_Id as actionId',
]};
let action2 = new Action();
action2.query().innerJoin('Employee', function () {
this.on('Action.created_By_Id', 'Employee.id')
.andOn('Employee.vendor_Id', bookshelf.knex.raw(1));
});
action2.query().innerJoin('ActionAssignedTo', function () {
this.on('Action.id', 'ActionAssignedTo.action_Id')
.andOn('ActionAssignedTo.action_Id', bookshelf.knex.raw(5));
});
action2.query().where(function() {
this.where('Action.created_By_Id', empId)
});
action2.query().groupBy('Action.id');
action2.query().limit(2);
action2.query().columns(options.columns);
let action1;
action1 = Action.where('id', actionId);
action1.query().columns('id');
return bookshelf.knex.raw('select * from '
+ '(' + action1.query().toString() + ') AS act1'
+ ' left Outer Join '
+ '(' + action2.query().toString() + ') AS act2'
+ ' on act1.id = act2.actionId');
I am not keen on using bookshelf.knex.raw for using the left Outer Join as the output given by knex.raw and bookshelf differ.
Is there a way I can do the 'left Outer Join' directly using bookshelf library.
I looked into the code but it seems leftOuterJoin only takes table name as the first parameter and what I need is a query.
I think your main problem is that you're using Bookshelf like you would be using knex. Bookshelf is meant to be used with models you would define and then query on them.
Here is an example of what you should have as model
// Adding registry to avoid circular references
// Adding camelcase to get your columns names converted to camelCase
bookshelf.plugin(['bookshelf-camelcase', 'registry']);
// Reference: https://github.com/brianc/node-pg-types
// These two lines convert all bigint values coming from Postgres from JS string to JS integer.
// Removing these lines will mess up with Bookshelf count() methods and bigserial values
pg.types.setTypeParser(20, 'text', parseInt);
const Action = db.bookshelf.Model.extend({
tableName: 'Action',
createdBy: function createdBy() {
return this.belongsTo(Employee, 'id', 'created_By_Id');
},
assignedTo: function assignedTo() {
return this.hasMany(ActionAssignedTo, 'action_id');
},
});
const Employee = db.bookshelf.Model.extend({
tableName: 'Employee',
createdActions: function createdActions() {
return this.hasMany(Action, 'created_By_Id');
},
});
const ActionAssignedTo = db.bookshelf.Model.extend({
tableName: 'ActionAssignedTo',
action: function action() {
return this.belongsTo(Action, 'id', 'action_Id');
},
employee: function employee() {
return this.belongsTo(Employee, 'id', 'employee_Id');
},
});
module.exports = {
Action: db.bookshelf.model('Action', Action),
Employee: db.bookshelf.model('Employee', Employee),
ActionAssignedTo: db.bookshelf.model('ActionAssignedTo', ActionAssignedTo),
db,
};
You would then be able to fetch your results with a query like this
const Model = require('model.js');
Model.Action
.where({ id: 3 })
.fetchAll({ withRelated: ['createdBy', 'assignedTo', 'assignedTo.employee'] })
.then(data => {
// Do what you have to do
});
What your want to achieve is not possible with only one query in Bookshelf. You probably need to do a first query using knex to get a list of Action ids and then give them to Bookshelf.js
db.bookshelf.knex.raw(`
select ActionAssignedTo.action_Id as actionId,
from Action
inner join Employee
on Action.created_By_Id = Employee.id
and Employee.vendor_Id = ?
inner join ActionAssignedTo
on Action.id = ActionAssignedTo.action_Id
and ActionAssignedTo.action_Id = ?
where Action.created_By_Id = ?
group by Action.id
limit ?`,
[2, 3, 7, 2]
)
.then(result => {
const rows = result.rows;
// Do what you have to do
})
And then use the recovered Ids to get your Bookshelf query like this
Model.Action
.query(qb => {
qb.whereIn('id', rows);
})
.fetchAll({
withRelated: [{
'createdBy': qb => {
qb.columns(['id', 'firstname', 'lastname']);
},
'assignedTo': qb => {
qb.columns(['action_Id', 'employee_Id']);
},
'assignedTo.employee': qb => {
qb.columns(['id', 'firstname', 'lastname']);
},
}],
columns: ['id', 'name', 'completed_At', 'deadline', 'notes']
})
.fetchAll(data => {
// Do what you have to do
});
Note that the columns used for joins MUST BE in the columns list for each table. If you omit the columns, all the columns will be selected.
By default, Bookshelf will retrieve all columns and all root objects. The default is kind of LEFT OUTER JOIN.

Help building up LINQ2SQL query which has joins

I have this:
var q = (from order in db.Orders
from payment in db.Payments
.Where(x => x.ID == order.paymentID)
.DefaultIfEmpty()
from siteUser in db.SiteUsers
.Where(x => x.siteUserID == order.siteUserID)
.DefaultIfEmpty()
where siteUser.siteUserID != null
select new
{
order.orderID,
order.dateCreated,
payment.totalAmount,
siteUser.firstName,
siteUser.lastName
});
I want to add on to it like this:
switch (_qs["sort"])
{
case "0":
q = q.OrderByDescending(x => x.dateCreated);
break;
case "1":
q = q.OrderBy(x => x.dateCreated);
break; ...
I've done this before with a single table, but the multiple tables in the first code block force me to specify a select statement which causes it to be an anonymous type. How can this be done?
Note: I even tried to make a class with the properties that i'm selecting and casting the query to this type, still a no go.
Not sure I understand the question but the code you pasted looks valid to me.
I checked:
var q = (
from order in db.Orders
join payment in db.Payments on
order.paymentID equals payment.ID into payments
from payment in payments.DefaultIfEmpty()
join siteUser in db.SiteUsers on
order.siteUserID equals siteUser.siteUserID into siteUsers
from siteUser in siteUsers.DefaultIfEmpty()
where siteUser.siteUserID != null
select
new
{
order.orderID,
order.dateCreated,
payment.totalAmount,
siteUser.firstName,
siteUser.lastName
});
switch (sort)
{
case "0":
q = q.OrderByDescending(x => x.dateCreated);
break;
case "1":
q = q.OrderBy(x => x.dateCreated);
break;
}
var restult = q.ToList();
This works.