I have a string that has a query.
The problem is I cannot just append to it, after the where clause there is a group by.
So say i'm given this string:
var query = "select stuff from db where something = 3 group by stuff"
Now I want to append "somethingelse > 5 AND "
Result:
query = "select stuff from db where somethingelse > 5 AND something = 3 group by stuff"
What do I need to do to do this? Thanks
query = query.replace(/where/,'where somethingelse > 5 AND');
David's answer is the most pragmatic if you are passed the query string as-is.
Alternatively, if you're building it up yourself it may be better to allow the list of selectors, query constraints etc. to be passed in so that you create a correct query string initially. Something a bit like:
val query = "select " + selectors.join() +
" from " + tables.join() +
" where " + constraints.join() +
" group by " + groupings.join()
Related
I have a simple sql query where I am trying to allow my employees to have the ability to search for other employees in my db. I want them to be able to search by both, or either first/last name. I have this, but it's not working.
var selectEmployee = "select * from employees where UPPER(FIRSTNAME, LASTNAME) LIKE UPPER('%" + req.body.search + "%')"
so how would I search through both first and last name using the req.body.search value I am passing back?
thanks.
Use OR
var selectEmployee = "select * from employees where FIRSTNAME LIKE '%" + req.body.search + "%' OR LASTNAME LIKE '%" + req.body.search + "%'"
you may use UPPER function
I am writing a script to take a stock number, loop through existing stock numbers until a match is NOT found, then assign that unique stock number to the record. My problem is that the usual data[i][2] doesn't seem to reference a 'query' the same way that Apps Script would reference an array.
Fair warning, I'm trying to expand my Apps Script skills in to broader Javascript so I there's a good chance I'm doing it all wrong - I'm all ears if you tell me I'm doing this all incorrectly!
Using the log: data[i][2] gives me 'undefined' whereas data[2] gives me all fields of the third item in my query. Based on this I feel like I just need to learn how to reference it properly.
//Querying my datasource as 'var data'
var query = app.models.UsedVehicles.newQuery();
query.filters.ParentDealType._contains = prefix;
var data = query.run();
//Returns four records which is correct.
var testStockNo = prefix+month+countstring+year;
console.log("Test Stock Number " + j + ": " + testStockNo);
for (i = 0; i < data.length; i++){
console.log("data[i][2]: " + data[i][2]); //results: undefined
console.log("data[2]: " + data[2]); //results: all fields of 3rd query result.
if(data[i][2] === testStockNo){
k++;
break;
}else{
console.log("No Match");
}
}
Even if testStockNo equals the value in field:TStockNo, the log displays:
Test Stock Number 1: C1200118
data[i][2]: undefined
data[2]: Record : { TIndex: 8, TVin8: HS654987, TStockNo: null,
TParentStkNo: GSD6578, TYear: 2010, TMake: NISSAN, TModel: PICKUP,
TMileage: 24356, ParentDealType: C}
No Match
Issue/Solution:
query.run() returns array of records and NOT a array of arrays(2D). You should access the Record value using it's key instead of a index.
Snippets:
console.log("data[i][TStockNo]: " + data[i]['TStockNo']);
console.log("data[i].TStockNo: " + data[i].TStockNo);
console.log("data[2]: " + data[2]);
References:
Query#Run
i have a select query to a local database and for some reason the following error shows up:
ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'FROM site WHERE name = OCC AND date_start = 2018-07-30 08:00:00 AND date_end = '' at line 1
here's my query:
connection.query("SELECT *, FROM shop WHERE name = " + shop_name + " AND date_start = " + myDate + " AND date_end = " + myDate2, function (err, result)
{
if (err)
{
console.log("Error Is:" + err);
}
else
{
console.log('DATA EXISTING IS =' + JSON.stringify(result));
}
});
am i missing something?
The usual mantra: use parameterized queries. They will prevent SQL injections and make your service more secure. Furthermore they will take care of the usual pitfalls when building a query using string concatenation.
Let's have a look at your query
"SELECT *, FROM shop WHERE name = " + shop_name + " AND date_start = " + myDate + " AND date_end = " + myDate2
Which spells out to something like
SELECT *, FROM shop WHERE name = myshop AND date_start = 2018-07-30 AND date_end = 2018-08-10
There are at least 3 errors
The , behind the SELECT * this is also the one the error tells you about. I suppose you had a column list and replaced it with *
The shop name column is most certainly some char column. So you have to enclose your values with quotes
Also the dates must be used with quotes, so the SQL engine will parse it to a date and do the comparison. For some SQL engines there is also a special annotation for dates. Have a look in the documentation.
This query should work
"SELECT * FROM shop WHERE name = '" + shop_name + "' AND date_start = '" + myDate + "' AND date_end = '" + myDate2 +"'"
depending on what myDate and myDate2 are.
At least problems 2 and 3 would not happen if you use parameterized queries. Consult the documentation of the library you are using.
My sequelize query always returns 0 results,
but when I copy/paste the exact same query into psql it works fine, returning the correct rows exactly as expected
return sequelize.query(
"SELECT * FROM orders" +
" INNER JOIN sizes ON orders.sizeid = sizes.sizeid" +
" INNER JOIN types ON sizes.typeid = types.typeid" +
" INNER JOIN items ON types.itemid = items.itemid" +
" WHERE orders.fbid = :fbid AND pickuptime >= :today" +
" ORDER BY orders.pickuptime ASC",
{ replacements: {fbid, today}, type: sequelize.QueryTypes.SELECT }
);
fbid is an integer & today is a string of shape 'yyyy-mm-dd'
If I drop the 'today' condition, I get rows returned
Is sequelize escaping my date string?
If you defined named parameter like it fbid=:fbid in the SQL script,
you should pass an object {fbid: 'fbid_value'},
or if you defined unnamed parameters fbid=?, you should pass an array ['fbid_value'].
Here's docs http://docs.sequelizejs.com/en/latest/api/sequelize/#querysql-options-promise
Try to pass an object to replacement:
return sequelize.query(
"SELECT * FROM orders" +
" INNER JOIN sizes ON orders.sizeid = sizes.sizeid" +
" INNER JOIN types ON sizes.typeid = types.typeid" +
" INNER JOIN items ON types.itemid = items.itemid" +
" WHERE orders.fbid = :fbid AND pickuptime >= :today" +
" ORDER BY orders.pickuptime ASC",
{ replacements: {fbid: 'fbid_value', today: 'today_value'}, type: sequelize.QueryTypes.SELECT }
);
So i'm using multiple if statements to draw data from a database based on the users search criteria.
What i'm struggling with is
if(request.getParameter("searchProperty")!= ""){
SearchStatement = "town_city = '" + request.getParameter("searchProperty") + "'";
if(request.getParameter("bedrooms") != "0"){
SearchStatement += " AND bedrooms = '" + request.getParameter("bedrooms") + "'";
}
}
with the idea that this concatenates a string to use as a query in the database, and bring back the results the user is searching for (this is a property searching website). I thought i'd done the if statement correctly. From what i understand, from what i've put, if the user were to select 0 in bedrooms it should return ALL results, but instead it returns NONE (who wants a house without a bedroom..) Can somebody explain what's going wrong please?
here's where the SQL statement is built and input
MyProperties = bookSQL.executeQuery("SELECT * FROM PROPERTIES WHERE " + SearchStatement);
with the expected outcome being, for example
SELECT * FROM PROPERTIES WHERE Location = 'input' AND Bedrooms = 'value'
unless value = 0 where it should just be
SELECT * FROM PROPERTIES WHERE Location = 'input'
i think the problem is with this statement,
request.getParameter("bedrooms") != "0"
should be something like this ,
(!request.getParameter("bedrooms").isEmpty())
Remember you are comparing the strings
so if is "0"
if(request.getParameter("bedrooms").equals("0")){
return SearchStatement ;
}
else {
SearchStatement += " AND bedrooms = '" + request.getParameter("bedrooms") + "'"
}
Hope this helps!!