'IN' query in fusion table - sql

In the following code, i want to add "IN" +Village+. Where to add this condition in the code. Variable village takes value from a drop down list based on that filter should occur.please help me.Village name is a column in my fusion table.
i.e select 'geometry',villageName from table where querypass > textvalue IN villagename='madurai'
function querymape()
{
/*variable holds the value*/
var village =document.getElementById('village').value.replace(/'/g, "\\'");
var operatore=document.getElementById('operatorstringe').value.replace(/'/g, "\\'");
var textvaluee=document.getElementById("text-valuee").value.replace(/'/g, "\\'");
var querypasse=document.getElementById('query-passe').value.replace(/'/g, "\\'");
{
layer.setQuery("SELECT 'geometry'," + querypasse + " FROM " + tableid + " WHERE " + querypasse + " " + operatore + " '" + textvaluee + "'"+"AND 'VillageName=+village+'");
}
}
/*This is my new code.But its not working.Please help me*/
function querymap()
{
//var villagename='';
var operator=document.getElementById('operatorstring').value.replace(/'/g, "\\'");
var textvalue=document.getElementById("text-value").value.replace(/'/g, "\\'");
var querypass=document.getElementById('query-pass').value.replace(/'/g, "\\'");
var searchStringe = document.getElementById('Search-stringe').value.replace(/'/g, "\\'");
{
layer.setQuery("SELECT 'geometry'," + querypass + " FROM " + tableid + " WHERE " + querypass + " " + operator + " '" + textvalue + "'"+"AND 'VillageName'="+ searchStringe+"");
}
}

Multiple conditions can be combined using the keyword "and"?
You twisted the IN syntax around, it is used when you want to match several values, if you only want to compare to a single value use "=" instead
Applied to your query (with IN syntax):
select 'geometry',villageName from table where querypass > textvalue and villagename IN ('madurai','another village')
With = syntax:
select 'geometry',villageName from table where querypass > textvalue and villagename = 'madurai'

Related

How to pass multiple values in a native query and retrieve that data in a Map<String, List<Data>>?

Here I want to pass a list of Ids and date as a parameter to the database query and I want the query to return data in a Map so the key is the id and List is the data against that id.
Query<Data> query = rdsSession.createNativeQuery(DBQueries.DATA_QUERY,
Data.class).setParameterList("performance_id", listOfIds).setParameter("fromdate", fromDate);
List<Data> listDBRecords = null;
Map<String, List<Data> records=listDBRecords.stream().collect(Collectors.groupingBy(Data::getId));
So how can I achieve this result by passing multiple values(ie. ids) in the query and return that data? This is the query I have written
public static final String SELECT_PORTFOLIO_SECURITY_DATA = "select capl.corporate_action_portfolio_level_id, " +
"capl.performance_id, capl.forwardlooking_sequence_no, " +
"capl.as_of_date, capl.price, casl.currency, capl.exchange_rate, " +
"capl.gross_dividend, capl.net_dividend, capl.sub_portfolio_guid, capl.effective_date, capl.adjustment_weighted_factor, capl.price_adjustment_factor, " +
"casl.share_adjustment_factor, casl.float_adjustment_factor, capl.index_shares, capl.input_tos_live, casl.input_float_live, capl.prediction_type from " +
ConfigurationManager.getProperties().getProperty("rdsConnection.schema") +
".corporate_action_portfolio_level capl inner join " +
ConfigurationManager.getProperties().getProperty("rdsConnection.schema") +
".corporate_action_security_level casl " +
"on capl.performance_id = casl.performance_id and capl.as_of_date = casl.as_of_date and capl.prediction_type = casl.prediction_type and " +
"capl.forwardlooking_sequence_no = casl.forwardlooking_sequence_no " +
"where capl.performance_id = :performance_id and capl.as_of_date = :as_of_date and capl.prediction_type = 'PREDICTED' or capl.prediction_type = 'LIVE'";
Can someone tell what is the right way?

How to create a dynamic query using collection-valued named parameters?

As the title suggests, i'm currently trying to add parts to the JPQL-query using collection-valued named parameters (:queryLst).
Function call:
List<PanelSet> psetLst = setRepository.getMaxZchnrGroupByLeftEight(p.getCustomerNumber(), p.getDrawingNumber(), queryLst);
queryLst:
// Is used to store values from scanned and convert them into parts of a query
ArrayList<String> queryLst = new ArrayList<>();
for (int i = 0; i < size1; i++) {
scanEdvRev = scanned.get(i).toString();
queryLst.set(i, "and left(a.drawingnumber, 8) != left('" + scanEdvRev + "', 8)");
}
SetRepository:
public interface SetRepository extends CrudRepository<PanelSet, Integer> {
#Query("select distinct max(a.drawingNumber) from PanelSet a "
+ "where a.customerNumber = :customerNumber "
+ "and a.drawingNumber != :drawingNumber (:queryLst) "
+ "group by left(a.drawingNumber, 8)")
List<PanelSet> getMaxZchnrGroupByLeftEight(#Param("customerNumber") String customerNumber,
#Param("drawingNumber") String drawingNumber,
#Param("queryLst") ArrayList<String> queryLst);
}
When i run the project i get the following exception:
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 159 [select distinct max(a.drawingNumber) from com.asetronics.qis2.model.PanelSet a where a.customerNumber = :customerNumber and a.drawingNumber != :drawingNumber (:queryLst) group by left(a.drawingNumber, 8)]
I'm unsure whether my approach to this problem is the correct way of doing this and whether this exception is caused by a simple syntax error or by my usage of collection-valued named parameters.
I've followed this guide trying to solve the problem.
EDIT: I'm basically trying to add each String from ArrayList<String> queryLst to the parametrized query inside setRepository.
#Query("select distinct max(a.drawingNumber) from PanelSet a "
+ "where a.customerNumber = :customerNumber "
+ "and a.drawingNumber != :drawingNumber (:queryLst) "
+ "group by left(a.drawingNumber, 8)")
If successful, the query behind the function
List<PanelSet> getMaxZchnrGroupByLeftEight(#Param("customerNumber") String customerNumber,
#Param("drawingNumber") String drawingNumber,
#Param("queryLst") ArrayList<String> queryLst);
should look like this:
queryStr = "select distinct max(a.drawingNumber) from PanelSet a "
+ "where a.customerNumber = " + customerNumber + ""
+ "and a.drawingNumber != " + drawingNumber + "";
for (String s : queryLst) {
queryStr = queryStr + s;
}
queryStr = queryStr + " group by left(a.drawingNumber, 8)";
I hope this clarifies what i'm trying to do with queryLst.
It can't be done using your approach of passing in a list of query chunks.
The closest you'll get is by adding every possible condition to the query and provide values for all those conditions in a way that allows conditions to be ignored, typically by providing a null.
You code might look like this:
#Query("select distinct max(a.drawingNumber) from PanelSet a "
+ "where a.customerNumber = :customerNumber "
+ "and a.drawingNumber != :drawingNumber "
+ "and a.myTextColumn = coalesce(:myTextColumn, a.myTextColumn) "
+ "and a.myIntegerColumn = coalesce(:myIntegerColumn, a.myIntegerColumn) "
// etc for all possible runtime conditions
+ "group by left(a.drawingNumber, 8)")
List<PanelSet> getMaxZchnrGroupByLeftEight(
#Param("customerNumber") String customerNumber,
#Param("drawingNumber") String drawingNumber,
#Param("myTextColumn") String myTextColumn,
#Param("myIntegerColumn") Integer myIntegerColumn);
Passing null for myTextColumn or myIntegerColumn will allow that column to be any value (except null).
You'll have to find SQL that works for the type of conditions you have and the data type of the columns involved and whether nulls are allowed.
If passing nulls doesn't work, use a special value, perhaps blank for text columns and some "impossible" date like 2999-01-01 fir date columns etc and code the condition like:
and (a.myCol = :myCol or :myCol = '2999-01-01')

Dynamic dates in where parameter

Am I able to use a dynamic date range for the "where" parameter? I'd like to get all the data changed in the last 30 mins.
All I can find in the documentation is using static dates:
https://developer.xero.com/documentation/api/requests-and-responses
You could try using the query string in the Where Clause.
For Ex.
string querystr = "Date >= " +
"DateTime(" + dateFrom.Year.ToString() + ",
" + dateFrom.Month.ToString() + ", " + dateFrom.Day.ToString() + ") " +
"&& Date <= " +
"DateTime(" + dateTo.Year.ToString() + ", "
+ dateTo.Month.ToString() + ", " + dateTo.Day.ToString() + ")";
Passing this querystring to retrieve user defined date rage Invoices

Generating SQL query that will ignore where clause if no condition is given in it using sequelize & node.js

I am using node.js as backend language & Microsoft SQL as database. And I am using sequelize (http://docs.sequelizejs.com) to query with SQL. Below is my Web API route handler code :
const sequelize = require('sequelize');
module.exports = {
getinfo(req, res) {
let {search, id, fromDate, toDate, firstName, lastName} = req.body;
const condition = "";
if(search != null && search != '')
{
condition += "id LIKE '%" + search + "%'";
condition += "fromDate LIKE '%" + search + "%'";
condition += "toDate LIKE '%" + search + "%'";
condition += "firstName LIKE '%" + search + "%'";
condition += "lastName LIKE '%" + search + "%'";
}
if(fromDate != null && toDate != null && fromDate != '' && toDate != '')
{
condition += "date BETWEEN" + fromDate + "AND" + toDate;
}
const query = "";
query = " SELECT * from TABLE where" + condition;
sequelize.query(query, type: sequelize.QueryTypes.SELECT)
.then( ...)
}
}
I wanted to make a scenario where even if condition is empty, the query should return the database. Initially I thought of using if in condition variable to check if condition variable has anything there or not.
if(condition != '' && condition != null) {
query = " SELECT * from TABLE where" + condition;
} else {
query = " SELECT * from TABLE " ;
}
But it wasn't working as expected (due to asynchronous nature of JavaScript). I want to make an SQL query itself that will check if there is any condition present in where clause or not, if not then it should return the whole table. Any help would be appreciated
The standard trick is to prepend 1=1 to the list of conditions. And (maybe) later append the extra conditions using AND condition:
const condition = " 1=1";
if(search != null && search != '')
{
condition += " AND id LIKE '%" + search + "%'";
condition += " AND fromDate LIKE '%" + search + "%'";
condition += " AND toDate LIKE '%" + search + "%'";
condition += " AND firstName LIKE '%" + search + "%'";
condition += " AND lastName LIKE '%" + search + "%'";
}
if(fromDate != null && toDate != null && fromDate != '' && toDate != '')
{
condition += " AND date BETWEEN " + fromDate + " AND " + toDate;
}
const query = "";
query = " SELECT * from TABLE where" + condition;
sequelize.query(query, type: sequelize.QueryTypes.SELECT) ...

SQL Join Query taking long to complete

I am working on a project that require me to join four tables. I have written this code but it's taking forever to finish. Please help. Ohhh I have about 121 000 entries in the Db
PortfolioCollectionDataContext context = null;
context = DataContext;
var Logins = from bkg in context.EnquiryBookings
where bkg.Paid == true
from log in context.Logins
where log.LoginID == bkg.LoginID
from enq in context.Enquiries
where enq.EnquiryID == bkg.EnquiryID
from estb in context.Establishments
where enq.EstablishmentID == estb.EstablishmentID
select new
{
log.LoginID,
log.FirstName,
log.LastName,
log.CountryOfResidence,
log.EmailAddress,
log.TelephoneNumber,
bkg.TotalPrice,
estb.CompanyName
};
string str = "";
foreach (var user in Logins)
{
str += ("[Name: " + user.LastName + " " + user.FirstName + " - Country: " + user.CountryOfResidence + " - Phone: " + user.TelephoneNumber + " - Email: " + user.EmailAddress + " - Booked From: " + user.CompanyName + " - Spent: " + user.TotalPrice.ToString() + "]");
}
return str;
Use following query on LINQ
PortfolioCollectionDataContext context = null;
context = DataContext;
var Logins = from bkg in context.EnquiryBookings
join log in context.Logins
on log.LoginID equals bkg.LoginID
&& bkg.Paid == true
join enq in context.Enquiries
on enq.EnquiryID equals bkg.EnquiryID
join estb in context.Establishments
on enq.EstablishmentID == estb.EstablishmentID
select new
{
str = "[Name: " + log.LastName + " " + log.FirstName + " - Country: " + log.CountryOfResidence + " - Phone: "
+ log.TelephoneNumber + " - Email: " + log.EmailAddress + " - Booked From: "
+ estb.CompanyName + " - Spent: " + bkg.TotalPrice.ToString() + "]"
};
string output = string.Join(", ", Logins.ToList());
return output;
Check your query by taking cursor on Logins and paste that query here. Then check an estimated execution plan of your query and paste here.
If using SQL Server, to get execution plan of your query using Sql server management studio, click on an icon highlighted in an image below.