I am using java java.sql.* for querying from SQLite DB. I found a starnge issue where I write a sqlString as:
SELECT n.Name as Name,
c.Value as Value0,
d.Value as Value1
FROM (Table1 c inner join Table2 n on c.NameID = n.ID),
Table3 d
WHERE c.RunID = 1
and d.RunID = 2
and c.NameID = d.NameID
The statement stmt.executeQuery(sqlQuery) throws the following exception:
java.sql.SQLException: no such column: n.Name
at org.sqlite.DB.throwex(DB.java:288)
at org.sqlite.NativeDB.prepare(Native Method)
at org.sqlite.DB.prepare(DB.java:114)
at org.sqlite.Stmt.executeQuery(Stmt.java:89).............
Name is already part of the Table2 table. The same statement is working fine from SQLite command prompt. But when I remove the open brackets and try to execute from java, there is no problem. Any idea why this happens so?
Try something like this, use sub resultset
SELECT rs1.Name AS NAME,
rs1.Value0 AS Value0,
d.Value AS Value1
FROM (SELECT n.Name AS NAME,
c.Value AS Value0,
d.Value AS Value1
FROM Table1 c INNER JOIN Table2 n ON c.NameID = n.ID) rs1,
Table3 d
WHERE c.RunID = 1
AND d.RunID = 2
AND c.NameID = d.NameID
The variables used in inner queries could not be referred outside. For example, you have used the variable n in inner sql. But you are referring it outside. The variable n is out of it's scope there.
Hi Friends Thanks for your fast responses. I am able to solve this problem. I am sharing this so if any1 else get this problem can do this:
SELECT ABC.Name as Name, ABC.Value as Value0, d.Value as Value1
FROM
(select n.Name as Name, c.Value as Value0 from Table1 c
inner join Table2 n on c.NameID = n.ID) AS ABC,
Table3 d ......;
Regards,Tor
Related
I want to execute a query against a MySQL database with Java. The code looks like this:
ResultSet resultSet = statement.executeQuery("select col1 from tb1 inner join tb2 on tb1.col2 = tb2.col3 where col4='"+foo+"'");
The query works perfectly when I use the shell but it doesn't work when I run it with Java because it says that col4 doesn't exist. But col4 exists.
I've just tried something like this;
select col1 from dbname.tb1 as a inner join dbname.tb2 as b on a.col2 = b.col3 where b.col4 = 'foo'
You should call the col4 with the table prefix "tb1" or "tb2".
As example:
select tb1.col1 from tb1 inner join tb2 on tb1.col2 = tb2.col3 where tb1.col4=...
The problem was not there. It was I little bit further:
ResultSet resultSet = statement.executeQuery("select col1 from tb1 inner join tb2 on tb1.col2 = tb2.col3 where col4='"+foo+"'");
myarray.add(resultSet.getString("col4"));//col4 can't exist here because it has not been selected
After executing the query I wanted to access a column that hadn't been selected.
I want to retrieve count and list of data in one query only which I want to write on JPA repository. I wrote it using a constructor and executed using entity manager, but it didn't work. It gave me a QuerySyntaxException. Here is my query:
String hql = "select new core.abc(select count(*) from abc as m where m.Id in :Ids and m.Type = :Type,"
+ "select max(m.modificationTime) from abc as m where m.Id in :Ids and m.Type = :Type )";
How can I write such kind of query in JPA repository?
I just figure out your use case senario is that you want to get all records from table as well as total-count of records and max value of a specific column , you named that column as modificationTime. So onething will be happen in this case, if you want to intract with table with single query, Than you will get useless data for both column named as max and count.
Try This for JPA,
#Query(value="SELECT cb from abc cd where cd.Id in (?1) and cd.Type=?2 , (SELECT MAX(m.modificationTime) as maxModificationTime , COUNT(*) as count FROM abc m where m.Id in (?3) and m.Type=?4) as m",nativeQuery=true)
SELECT
a.objid AS acctid,
a.acctno,
a.name,
a.meterid,
m.serialno,
(
SELECT
objid
FROM
waterworks_meter_reading r
WHERE r.meterid = a.meterid
AND r.month = 6
AND r.year = 2015
LIMIT 1
) AS readingid
FROM waterworks_account a
INNER JOIN waterworks_meter m ON a.meterid = m.objid
INNER JOIN waterworks_account_address ad ON a.objid = ad.parentid
WHERE ad.barangayid LIKE '%'
AND readingid IS NULL
When I tried to execute the query above it throws an error: Unknown column 'readingid' in 'where clause'. Can someone explain to me why?
In SQL, you cannot reference a column alias defined in a select in the where clause at the same level (or elsewhere in the select).
MySQL has a convenient work-around, in some cases. You can reference it in a having clause. So this should do what you want:
WHERE ad.barangayid LIKE '%'
HAVING readingid IS NULL
I think the problem is that the "readingid" isn't really a column name. It exists in the select but that happens after the where clause. I would use a nested query to get the "readingid" so it is available for the where clause.
For example:
SELECT
a.objid AS acctid,
a.acctno,
a.name,
a.meterid,
m.serialno FROM waterworks_account a
INNER JOIN waterworks_meter m ON a.meterid = m.objid
INNER JOIN waterworks_account_address ad ON a.objid = ad.parentid
WHERE ad.barangayid LIKE '%'
AND NOT EXISTS (SELECT
objid
FROM
waterworks_meter_reading r
WHERE r.meterid = a.meterid
AND r.month = 6
AND r.year = 2015)
I am getting this error when I am trying to execute this sql query
INSERT INTO
AGG_QUALITY
SELECT
QIF.DATEDM_ID,
'Status' AS BREAKDOWN_TYPE,
HCR.VALUE,
QIF.SCANDEFINITION_ID,
QIF.QUALITYISSUE_VALUE,
COUNT(QIF.QUALITYISSUEFACT_ID),
COUNT(QRF.QUALITYRESOLUTIONFACT_ID)
FROM
QUALITYISSUEFACT QIF,
HUBCODERECORD HCR,
ITEMSTATUS ITS
LEFT JOIN
QUALITYRESOLUTIONFACT QRF
ON
QIF.QUALITYISSUEFACT_ID = QRF.QUALITYISSUEFACT_ID
WHERE
QIF.DATEDM_ID > startDateDMId
AND QIF.DATEDM_ID <= endDateDMId
AND HCR.CODE = ITS.H_STATUS_TYPE
AND QIF.DIMENSION_ROM_PK = ITS.ITEMMASTER_ID
GROUP BY
QIF.DATEDM_ID, HCR.VALUE, QIF.SCANDEFINITION_ID, QIF.QUALITYISSUE_VALUE
;
DB21034E The command was processed as an SQL statement because it was not a
valid Command Line Processor command. During SQL processing it returned:
SQL0338N An ON clause associated with a JOIN operator or in a MERGE statement
is not valid. LINE NUMBER=31. SQLSTATE=42972
Try like below with inner joins:
INSERT INTO
AGG_QUALITY
SELECT
QIF.DATEDM_ID,
'Status' AS BREAKDOWN_TYPE,
HCR.VALUE,
QIF.SCANDEFINITION_ID,
QIF.QUALITYISSUE_VALUE,
COUNT(QIF.QUALITYISSUEFACT_ID),
COUNT(QRF.QUALITYRESOLUTIONFACT_ID)
FROM
QUALITYISSUEFACT QIF
INNER JOIN
HUBCODERECORD HCR
ON QIF.DIMENSION_ROM_PK = ITS.ITEMMASTER_ID
INNER JOIN
ITEMSTATUS ITS
ON QIF.DIMENSION_ROM_PK = ITS.ITEMMASTER_ID
LEFT JOIN
QUALITYRESOLUTIONFACT QRF
ON
QIF.QUALITYISSUEFACT_ID = QRF.QUALITYISSUEFACT_ID
WHERE
QIF.DATEDM_ID > startDateDMId
AND QIF.DATEDM_ID <= endDateDMId
GROUP BY
QIF.DATEDM_ID, HCR.VALUE, QIF.SCANDEFINITION_ID, QIF.QUALITYISSUE_VALUE
;
see if it helps
Had the same error here. (note, my Table1 has NO rows)
On my side I could solve it by changing the additional (comma separated) table2 to a REAL inner join.
Example from
select xxx from Table1 t1, Table2 t2
where (t2.col1 = t1.col1) and (t1.col2 = "whatever")
to
select xxx from Table1 t1
INNER JOIN Table2 t2 ON (t2.col1 = t1.col1)
where (t1.col2 = "whatever")
Hope this helps someone else.
(problem occured on DB2 9.7)
why do this query works directly on postgres database:
select m from medicine_case m WHERE m.id IN (select m.id FROM medicine_case m LEFT OUTER JOIN patient ON m.patient=patient.id ORDER BY patient.surname ASC )
AND in OpenJpa with the exact corresponding typed query:
String sql = " select m from medicine_case m WHERE m.id IN (select m.id FROM medicine_case m LEFT OUTER JOIN "
+ "patient ON m.patient=patient.id ORDER BY patient.surname ASC )";
TypedQuery<MedicineCase> query = persistenceClient.createQueryMC(sql);
setParameter(query);
query.setFirstResult(first);
query.setMaxResults(count);
gives me:
org.apache.openjpa.persistence.ArgumentException: Encountered "m . id IN ( select m . id FROM medicine_case m LEFT OUTER JOIN patient ON" at character 37, but expected: ["(", ")", "*",.... etc etc
why????? it's so strange and makes me crazy!
the code that creates the query from entity manager:
return entityManager.createQuery(sql, MedicineCase.class);
and the code that executes it:
return query.getResultList().iterator();
You're confusing SQL (which is what PostgreSQL expects) and HQL (which is what EntityManager.createQuery() expects).
Those are two different languages. SQL works with tables and columns, whereas JPQL works with JPA entities, fields/properties and associations, and is translated by your JPA implementation into SQL.
If you want to execute SQL, you must use EntityManager.createNativeQuery().
in jpql it becomes a bit different:
String sql = "select m from " + MedicineCase.class.getSimpleName() + " m WHERE m.id IN :mcList";
TypedQuery<MedicineCase> query = persistenceClient.createQueryMC(sql);
query.setParameter("mcList", persistenceClient.executeQueryMCId(persistenceClient.createQueryMCId(createSql()
+ addOrders())));
setParameter(query);
query.setFirstResult(first);
query.setMaxResults(count);
return persistenceClient.executeQueryMC(query);
where createSql returns:
sql.append("select m.id ").append(" FROM ").append(MedicineCase.class.getSimpleName()).append(" m");
and addOrders:
" LEFT OUTER JOIN m.patient p ORDER BY p.surname ASC