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.
Related
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
I want to get the number of users that have a lower number of XP points than the member who used the command, this way I can get his rank.
However I don't know much in javascript and sql queries, and I'm hard stuck with this, where it simply returns [object Object] instead of a number.
My sql table
const table = sql.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'scores';").get();
if (!table['count(*)']) {
// If the table isn't there, create it and setup the database correctly.
sql.prepare("CREATE TABLE scores (id TEXT PRIMARY KEY, user TEXT, guild TEXT, points INTEGER, level INTEGER, money INTEGER);").run();
// Ensure that the "id" row is always unique and indexed.
sql.prepare("CREATE UNIQUE INDEX idx_scores_id ON scores (id);").run();
sql.pragma("synchronous = 1");
sql.pragma("journal_mode = wal");
}
// And then we have two prepared statements to get and set the score data.
client.getScore = sql.prepare("SELECT * FROM scores WHERE user = ? AND guild = ?");
client.setScore = sql.prepare("INSERT OR REPLACE INTO scores (id, user, guild, points, level, money) VALUES (#id, #user, #guild, #points, #level, #money);");
});
My attempt
if (message.content.startsWith(prefix + "cl stats")) {
const curxp = score.points;
client.rank = sql.prepare("SELECT count(*) FROM scores WHERE points >= #curxp AND guild = #guild").get();
console.log(client.rank);
await message.reply(`${client.rank}`);
}
Found a solution. Probably not the best but it works.
client.getRank = sql.prepare("SELECT count(*) FROM scores WHERE points >= ? AND guild = ?");
function getRank(){
const curXP = score.points;
let rankOBJ = client.getRank.get(curXP, message.guild.id)
console.log(rankOBJ);
let rankStr = JSON.stringify(rankOBJ);
let rank = rankStr.match(/\d/g);
return rank;
};
I've got a problem with a sqlite query on node. The query with SqliteStudio is working, but with Node.js I get an empty array.
Here's the query:
const query =`
SELECT 'telephone' AS type,telephone AS data,CASE
WHEN telephone = (
SELECT data FROM customers_verified_contact_infos
WHERE type='telephone' AND data=j.telephone AND customer_id = ?
) THEN 'true'
ELSE 'false'
END AS verified
FROM customers j WHERE customer_id = ? AND telephone IS NOT NULL
UNION
SELECT 'email' AS type,email AS data,CASE
WHEN email = (
SELECT data FROM customers_verified_contact_infos
WHERE type='email' AND data=email AND customer_id = ?
) THEN 'true'
ELSE 'false'
END AS verified
FROM customers WHERE customer_id = ? AND email IS NOT NULL
UNION
SELECT 'fax' AS type,fax AS data,CASE
WHEN fax = (
SELECT data FROM customers_verified_contact_infos
WHERE type='fax' AND data=fax AND customer_id = ?
) THEN 'true'
ELSE 'false'
END AS verified
FROM customers WHERE customer_id = ? AND fax IS NOT NULL
UNION
SELECT type,data, 'true' AS verified
FROM customers_verified_contact_infos WHERE customer_id = ?
`;
I request two tables:
customers, with some customer information
customers_verified_contact_infos, with list contact information verified
Contact information can be in both or just one table.
The result is a list of rows with data, the type of data, and if it's been verified or not.
Now, the Node.js request:
db.all(query,[customer_id], (err, data) => {
console.log(data);
});
The data is an empty array and err = null.
With SqliteStudio, with the same query and customer, I get:
I tried SELECT by SELECT, and with case I didn't get a result. I don't find anything on internet which can help me.
If someone can help or give me advice, I'd appreciate it.
Thanks
The query has 7 ? placeholders, but the array [customer_id] only has one element. You need to repeat it for every placeholder.
db.all(query, Array(7).fill(customer_id), (err, data) => {
console.log(data);
});
I need your help. I am working on a web server with node.js and reactJS. I want to make a page for the Admin called "Users" to search for the users in the SQL database. I wrote a code that create two options to search Users by "Name" or "Country"
this is the code:
UserSearch: {
fields : {
firstname: {value:'', type:'text', label:"Name", placeholder:'type name', bluredBefore:false, validators:['non'], errorReport:[]},
country: {value:'-1', type:'select', label:"Country", placeholder:'select country', staticDataSource:'countries', bluredBefore:false, validators:['non'], errorReport:[]},
},
errorReport:false,
isWaiting : false,
queryTarget: 'userFind',
queryView: 'UserSearchGrid',
queryViewFields: 'userId, firstname, lastname ',
formCols:3,
notification: '',
},
UserSearchGrid: {searchForm:'UserSearch',
viewFields: ['userId','firstname','lastname'],
dataSource:[], count:0, offset:0, limit:10},
In the query file I wrote this code:
var where = {userId:userId,};
if (typeof args.firstname !== 'undefined' && args.firstname !== '')
where['firstname'] = args.firstname;
if (typeof args.country !== 'undefined' && args.country !== '-1')
where['country'] = args.country;
items = await UserProfile.findAndCountAll({
where: where, })
Now these two pieces of codes create a text-box "Name" and a drop-down menu "Country" and the Admin have to select the exact username and the correct country to get a result.
I need a sequelize query that let the Admin to enter the name (either first or last name) OR the country and get the result with any matching name or partially match or with the matching country.
Additional: I don't know if it possible, I want the to results to appear during that the admin is writing the name ( matching every typed letter and show the results ) . Thanks in advance for anyone can help.
Solved:
I Edited my if statement to be like this :
var where = {};
if (typeof args.firstname !== 'undefined' && args.firstname !== '')
// where['firstname'] = args.firstname;
where['$or']={firstname:{$like: `%${args.firstname}%`},lastname:{$like: `%${args.firstname}%`}};
items = await UserProfile.findAndCountAll({
where: where , })
(where) is an object that contains the clause (or), it do Select from database firstname or lastname containing (args.firstname) -that had been entered by the Admin-
Ex: I want to search for the user "John" in the database, if I typed "Jo" it will get the result with all users that have "John" as their firstname or lastname from database as they containing "Jo" in their name.
I have a Postgresql stored function defined as following:
CREATE OR REPLACE FUNCTION SessionGet(
sid varchar)
RETURNS "SESSION" AS $$
SELECT * FROM "SESSION" WHERE "SESSION_ID" = sid;
$$ LANGUAGE sql;
I call it from node using the PG module with:
SELECT SessionGet('SID-1'::varchar);
The session table is defined as:
CREATE TABLE "SESSION"
(
"SESSION_ID" character varying NOT NULL DEFAULT ''::character varying,
"SESSION" json NOT NULL DEFAULT '{}'::json,
"LAST_UPDATE" bigint DEFAULT 0,
CONSTRAINT "SESSION_PK" PRIMARY KEY ("SESSION_ID")
)
WITH (
OIDS=FALSE
);
I am trying to retrieve the returned result as following:
client.query(sql, function(err, result) {
done(); // Releasing connection to the pool
if ( err ) {
callback(err);
} else if ( result.rows.length > 0 ) {
var ttmp = result.rows[0];
var tmp1 = ttmp[0];
console.log("Res[0]: " + tmp1);
callback(err,result.rows[0]);
} else {
callback(err);
}
});
Although result.rows.length is > 0, result.rows[0][0] is undefined. How can I retrieve the field values from the returned row?
I have solved my issue by sending a SQL statement (SELECT * FROM "SESSION" WHERE "SESSION_ID" = '...';) rather than relying on a stored function.
I have also changed the name of the SESSION column to SESSION_JS, as giving the name of a table to a column too seems to be an issue, though no error message is displayed.