Mysql query with In clause regex - java

I have a SQL query like this:
"select f.filterid as filtename, f.id as filtertext " +
"from filter f " +
"where group_Id = '" + id +"' " +
"OR groupIds like '%." + id + ".%' ";
And I want to pass a list of ids to this query to make performance better. I don't know whether REGEX works with in an IN clause. And I tried the below one which is not working and not sure what to use in case of REGEX.
"select f.filterid as filtename, f.id as filtertext from filter f " +
"where group_Id in ("+StringUtils.join(ids, "','")+")" +
"OR groupIds in ("+StringUtils.join(ids, "','")+")"";
Thanks.

I would recommend to use the Query#setParameter to achieve this, if you are using JPA you can easily supply your ids list in the setParameter.
But for your current resolution you may try the below changes.
Not sure if your group_Id column expects integer or string datatype, well I will propose changes for either of the cases.
If it expects String - You are missing the starting " ' " change your code as below
If it expects integer type - You should not wrap your comma separator with " ' ", remove them as below
"select f.filterid as filtename, f.id as filtertext from filter f " + "where group_Id in ("+StringUtils.join(ids, ",")+")" + "OR groupIds in ("+"'"+StringUtils.join(ids, "','")+"'"+")";
Trying running this query and see if you get the desired resultset

Perhaps the problem lies in the use of method StringUtils.join.
you can edit your sql like the following code.
select f.filterid as filtename, f.id as filtertext from filter f where group_Id in ('groupA_id', 'groupB_id', 'groupC_id')
if your ids is {"groupA_id", "groupB_id", "groupC_id"}, then
"select f.filterid as filtename, f.id as filtertext from filter f where group_Id in (" + "'" + StringUtils.join(ids, "','") + "'" +")"

Try Something like this:
Query query = session.Query("select f.filterid as filtename, f.id as filtertext from filter f where group_Id in :list");
query.SetParameterList(":list", ListOfIds);

Related

Querying two tables in a database with Java

I have been defeated by the great SQL boss and am now requesting assistance.
Ive removed spaces in table names to avoid confusion
Anyways, I have two tables Orders and Order Details. I need to query a few columns from both. So far, I can query Orders just fine, but when it comes to querying Order Details, or the two together, I get errors.
My Question is this: How do I query two tables?
(note: semicolon is at the bottom, imagine it's there)
Here's what works so far on Orders:
String queryString = "select `Order Date`, Freight "
+ "from Orders "
+ "where Orders.`Order ID` = ? "
Here's my attempt to just grab one column from Order Details and the error to follow
String queryString = "select Product "
+ "from `Order Details` "
+ "where `Order Details`.`Order ID` = ? "
net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::4.0.1 user lacks privilege or object not found: ORDER DETAILS.ORDER ID
at net.ucanaccess.jdbc.UcanaccessConnection.prepareStatement(UcanaccessConnection.java:528)
Here's my attempt to grab both at once and the error to follow
String queryString = "select `Order Date`, Freight, Product "
+ "from Orders, `Order Details` "
+ "where Orders.`Order ID` = ? "
net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::4.0.1 user lacks privilege or object not found: PRODUCT
at net.ucanaccess.jdbc.UcanaccessConnection.prepareStatement(UcanaccessConnection.java:528)
Here's the above attempt with an extra line at the bottom combining them (I don't know what this does), but it alters the error.
String queryString = "select `Order Date`, Freight, Product "
+ "from Orders, `Order Details` "
+ "where Orders.`Order ID` = ? "
+ "and Orders.`Order ID` = `Order Details`.`Order ID`"
net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::4.0.1 user lacks privilege or object not found: ORDER DETAILS.ORDER ID
at net.ucanaccess.jdbc.UcanaccessConnection.prepareStatement(UcanaccessConnection.java:528)
Putting the table name in quotes doesn't work in any SQL-Server i know without changing some configuration.
The correct way is using []:
MSSQL-Example:
SELECT * FROM [Order Details]
Your query may look like this:
String queryString = "SELECT Product "
+ "FROM [Order Details] "
+ "WHERE `Order ID` = ? "
But i would suggest to work without whitspaces within any identifier.
Read about JOIN statements, this will allow you to work with two tables. Try use something like “SELECT your_columns FROM orders o JOIN orderDetails od ON o.id = od.order_id”.
Errors like “object not found” means you didn’t create table. Wish it’ll help.

SQL MERGE to update or insert values into same table

"MERGE INTO NT_PROPERTY ntProp USING ( " +
"SELECT * FROM NT_PROPERTY ) " +
"VALUES " +
"('minDPTObjectId'," + minDPTObjectId + ", 'Starting DPT Object Id') " +
"('maxDPTObjectId', " + maxDPTObjectId + ", 'Ending DPT Object Id') " +
"vt (NAME, VALUE, NOTE) " +
"ON ( ntProp.NAME = vt.NAME ) " +
"WHEN MATCHED THEN " +
"UPDATE SET VALUE = vt.VALUE "+
"WHEN NOT MATCHED THEN " +
"INSERT (NAME, VALUE, NOTE) VALUES (vt.NAME, vt.VALUE, vt.NOTE)";
Well I'm getting a missing ON keyword error and with no clue what so ever, also is there any other way to make it less clumsy
Help is very much appreciated.
The problem is that your MERGE syntax is incorrect. Your statement takes the form of:
MERGE INTO nt_property ntprop
USING (SELECT * FROM nt_property)
VALUES (...)
vt (...)
ON (ntprop.name = vt.name)
WHEN MATCHED THEN
UPDATE ...
WHEN NOT MATCHED THEN
INSERT ...;
but it should be of the form:
MERGE INTO target_table tgt_alias
USING source_table_or_subquery src_alias
ON (<JOIN conditions>)
WHEN MATCHED THEN
UPDATE ...
WHEN NOT MATCHED THEN
INSERT ...;
Why do you have the VALUES and vt clauses between your using and your on clauses? That's the incorrect syntax. Also, whilst you can use select * from tablename in the using clause, you could just use the tablename directly, since you're selecting all columns and all rows.
MERGE INTO NT_PROPERTY D
USING (SELECT * FROM DUAL ) S
ON (D.NAME = 'minDPTObjectId')
WHEN MATCHED THEN UPDATE SET D.VALUE = '1234'
WHEN NOT MATCHED THEN INSERT (NAME, VALUE, NOTE)
VALUES ('maxDPTObjectId', '1111', 'Ending DPT Object Id') ;

Query in Java - Subquery gone wrong or what?

I'm having a problem with this query of mine. I've spent almost an hour trying to correct it but still getting an error.
Heres my code:
sql = "INSERT INTO tbl_case \n" +
"(Case_ID, Employee_ID, Patient_ID, Chief_Complaint, Date) \n" +
"VALUES \n" +
"(\n" +
" '',\n" +
" 'EMP0001',\n" +
" '(SELECT Patient_ID from tbl_patient WHERE ID_no = '"+getPatient_ID()+"')',\n" +
" '"+txtcc.getText()+"',\n" +
" '"+time+"'\n" +
")";
dp.sop("Query 'Create Case': "+sql);
dp.Insertion(sql);
Note: dp stands for a class I inherited the methods from. dp.Selection is a simple executeQuery I made for retrieving data. dp.Insertion is for updating.
Here is the output of the query in String:
Query 'Create Case': INSERT INTO tbl_case
(Case_ID, Employee_ID, Patient_ID, Chief_Complaint, Date)
VALUES
(
'',
'EMP0001',
'(SELECT Patient_ID from tbl_patient WHERE ID_no = '10000201117')',
'Head Ache',
'2016-01-30 09:55:27'
)
and the error is a mysql syntax error near:
'10000201117)',
'Head Ache',
'2016-01-30 10:07:08'
)' at Line 7
anyone spotted whats wrong? I'm using mysql from xampp.
Since (SELECT Patient_ID from tbl_patient WHERE ID_no = '10000201117') is in single quotes you might want to try putting 10000201117 in double quotes.
For example:
'(SELECT Patient_ID from tbl_patient WHERE ID_no = "10000201117")'
I don't think you need to surround the SELECT statement with quotes.
As it is now, this part '(SELECT Patient_ID from tbl_patient WHERE ID_no = ' is interpreted as a value instead of part of a query.
Try: (SELECT ...) instead of '(SELECT ...)'

Android - SQLiteException: near "=": syntax error (code 1)

I am trying to log id from users table and jobname from jobs table using user id
String select = "SELECT jobname FROM " + TABLE_JOBS+ "where userid =" +myid;
"SELECT jobname FROM " + TABLE_JOBS+ "where userid =" +myid;
You need whitespace between identifiers such as your table name and keywords such as where:
"SELECT jobname FROM " + TABLE_JOBS+ " where userid =" +myid;
You're missing a whitespace before the where clause, so it gets appended directly to the table name, and you effectively don't have a where clause:
String select = "SELECT jobname FROM " + TABLE_JOBS+ " where userid =" +myid;
// whitespace was missing here -----------------------^

Named Query to SELECT rows with MAX(column name), DISTINCT by another column

I have a case similar to the one described in this question, I wrote an identical query which works, but when I try to write it as a jpql named query, I'm getting an error.
My query:
#NamedQuery(
name = "findRankingsBetween",
query = "SELECT rt FROM Rankingtable rt " +
"INNER JOIN " +
"(SELECT teamId, MAX(lastupdate) as MaxDateTime " +
"FROM Rankingtable " +
"GROUP BY teamId) grouped " +
"ON rt.teamId = grouped.teamId " +
"AND rt.lastupdate = grouped.MaxDateTime " +
"WHERE rt.lastupdate BETWEEN :from AND :to"
)
Error:
Error in named query: findRankingsBetween: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 79
How to write the query properly in jpql?
As noted in this answer, a subquery in JPQL can only occur in select and where clauses.
Hibernate doc.
An equivalent query in JPQL is:
"SELECT rt FROM Rankingtable rt " +
"WHERE rt.lastupdate = (SELECT MAX(r2.lastupdate) " +
"FROM Rankingtable r2 " +
"WHERE r2.teamid = rt.teamid) " +
"AND rt.lastupdate BETWEEN :from AND :to"

Categories