Subquery - on clause column not visible - java

I facing with a strange situation with a sql query on mysql 5.1.41 environment on a Ubuntu machine.
The code follow
SELECT spedizione0_.idspedizione,
spedizione0_.*,
(
SELECT COUNT(n.idnegozio)
FROM negozio n
LEFT JOIN confezione c
ON n.idnegozio = c.idnegozio
AND c.idspedizione = spedizione0_.idspedizione
WHERE n.datainizio <= spedizione0_.dataspedizione
AND n.datafine >= spedizione0_.dataspedizione
OR c.idspedizione != 0
) AS formula5_
FROM orocashgenerico.spedizione spedizione0_
ORDER BY spedizione0_.dataspedizione DESC
In this case the error says : [Err] 1054 - Unknown column 'spedizione0_.idspedizione' in 'on clause'
The only way to run this query is to change the .. on n.idnegozio=c.idnegozio and c.idspedizione=spedizione0_.idspedizione into on n.idnegozio=c.idnegozio and c.idspedizione=12
The most strange things for me is: if i move the and condition to the where clause the query run correctly, of course the results is not what I excepted.
My question is where is the problem?
Is something related to the MySQL version?

It's because spedizione0_ is not found with the scope of your subquery. Try this one,
SELECT spedizione0_.idspedizione, // add additionl columns
COUNT(n.idnegozio) AS formula5_
FROM spedizione spedizione0_
LEFT JOIN confezione c
ON c.idspedizion = spedizione0_.idspedizione
LEFT JOIN negozio n
ON n.idnegozio = c.idnegozio
WHERE (
n.datainizio <= spedizione0_.dataspedizione AND
n.datafine >= spedizione0_.dataspedizione
)
OR c.idspedizione != 0
GROUP By spedizione0_.idspedizione
ORDER BY spedizione0_.dataspedizione DESC

as I can see, you are using the wrong syntax here. When you use a Left Outer join, you cannot mention more than one condition in ON clause.
In your case, you need to use one more Left join clause after that ON clause to join 3rd table which is giving error.

Related

Hibernate subquery problem with aggregate function

I'm trying to run this query within Hibernate (through JPA) but it throws
Caused by: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 32
Any way to make this work or make it better ? I would not want to use OR clause because the query is much slower when using that.
SELECT SUM(s) as sum FROM (
SELECT count (ID) AS s
FROM TABLE1 rr
WHERE rr.status = 0
AND (rr.risk = '1' AND rr.rate = '222' )
UNION ALL
SELECT count (ID) AS s
FROM TABLE1 rr
WHERE rr.status = 0
AND (rr.risk = '2' AND rr.open = '222' ))
With HQL queries, Hibernate ORM doesn't support subqueries in the FROM clause (you can use them in the WHERE clause).
If you cannot rewrite this query as HQL without the subquery (for performance reasons, for example), I think it's OK to run it on the db as a native SQL query:
String sqlQuery = ...;
session.createNativeQuery(sqlQuery).getSingleResult();

JPQL unexpected AST node: around "coalesce"

JPQL got an error : threw
org.springframework.dao.InvalidDataAccessApiUsageException
(org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected AST
node: ( near line 3, column 48 ) select invoiceBE from InvoiceBE
invoiceBE where invoiceBE.institutionId = ?1 and
coalesce(invoiceBE.paidActivity.date < ?2) and
invoiceBE.exportedActivity.date < ?3 order by
invoiceBE.vendorInvoiceNumber asc
Is there any error around "coalesce"?
I run the sql well in mysql database.
select
* from
ACQ_INVOICE invoice
where
invoice.institution_id=91475
and coalesce(invoice.`user_paid_date` < '2020-01-20', invoice.`paid_date` < '2020-01-20T16:45:40.786Z')
Thanks.
The coalesce expression looks all wrong.
I don't think back ticks to quote a property are allowed. That looks more like MySQL SQL syntax.
I'm also not completely sure if COALESCE may be used with boolean expressions.
Changed to
coalesce(invoice.user_paid_date, invoice.paid_date)< '2020-01-20'
And it worked.

Java SQLException SQL0901 and AS400 MCH1210 errors

I'm running a rather large query (~83k results) through my Java Application that is producing the following error:
java.sql.SQLException: [SQL0901] SQL system error. Cause . . . . . : An SQL system er
ror has occurred. The current SQL statement cannot be completed successfully. The error will not prevent other SQL statements from being processed. Previous messages may indicate that there is a problem with the SQL statement and SQL did not correctly diagnose the error. The previous message identifier was MCH1210. Internal error type 3002 has occurred. If precompiling, processing will not continue beyond this statement. Recovery: See the previous messages to determine if there is a problem with the SQL statement. To view the messages, use the DSPJOBLOG command if running interactively, or the WRKJOB command to view the output of a precompile. An application program receiving this return code may attempt further SQL statements. Correct any errors and try the request again.
From this page, it appears as though Error SQL0901 means I may have a Driver issue.
Digging into the MCH1210 error, yielded this StackOverflow question so I thought that maybe I would have the same issue, however there are a few differences.
When I attempt to run my query in the System iNavigator, it works just fine. When it runs in my application, I get the above error.
This is my query:
SELECT
DWVNDN, DWINVN, DWDTEI, DWRTPE, DWINAM, DWCHKN, DWJCDE
FROM HSDATA4.DWRECAP
WHERE DWDTEI > 20180901 AND (DWRTPE = 2 OR DWRTPE = 3) AND DWINVN IN
(SELECT DW.DWINVN
FROM HSDATA4.DWRECAP DW
INNER JOIN HSDATA4.FXVNDCP FX ON DW.DWVNDN = FX.FXVNDN
WHERE DW.DWRTPE = 1 AND DW.DWDTEI BETWEEN 20180904 AND 20190904)
ORDER BY DWDTEI ASC, DWVNDN ASC;
I should note that when changing the inner query from SELECT ... to SELECT COUNT(*) to get a tally of records coming back, the returned value is 83314, so the main query is using over 83k parameters.
I was originally going to ignore it because I was getting results, however it appears that some of the results end up getting cut off so I don't know how to proceed.
Also, if you hate the column names in the database...so do I. It wasn't my choice...
Doesn't the inner join give you everything that you need?
SELECT
DW.DWVNDN, DW.DWINVN, DW.DWDTEI, DW.DWRTPE, DW.DWINAM, DW.DWCHKN, DW.DWJCDE
FROM HSDATA4.DWRECAP DW
INNER JOIN HSDATA4.FXVNDCP FX ON DW.DWVNDN = FX.FXVNDN
WHERE DW.DWRTPE = 1 AND DW.DWDTEI BETWEEN 20180904 AND 20190904
AND DW.DWDTEI > 20180901 AND DW.DWRTPE IN (2,3)
ORDER BY DW.DWDTEI ASC, DW.DWVNDN ASC;
How about an outer join
SELECT
DW2.DWVNDN, DW2.DWINVN, DW2.DWDTEI, DW2.DWRTPE, DW2.DWINAM, DW2.DWCHKN, DW2.DWJCDE
FROM
(( HSDATA4.DWRECAP DW INNER JOIN HSDATA4.FXVNDCP FX
ON DW.DWVNDN = FX.FXVNDN AND DW.DWRTPE = 1
AND DW.DWDTEI BETWEEN 20180904 AND 20190904)
LEFT OUTER JOIN HSDATA4.DWRECAP DW2
ON DW.DWVNDN = DW2.DWVNDN
AND DW2.DWDTEI > 20180901 AND DW2.DWRTPE in (2,3))
The inner join selects the initial invoice type of 1 between your valid date ranges and the left outer join selects matching invoice numbers where there was a modification

Error Only from Java Spark ORA-00918: column ambiguously defined

I am trying to run few SQL queries using Java Spark libraries.
All SQLs are running fine except one:
(SELECT CMM.BENEFIT, (length(CMM.HIERARCHY) - length(replace(CMM.HIERARCHY,'>','')) + 1) BNFT_CMPNT_LVL_NBR, LBCX.SERVICE_DEF_TGT_CD, LBCX.SERVICE_DEF_DESC, LBCX.BENEFIT_CMPNT_DESC, LBCX.SERVICE_DEF_TGT_CD, CMM.HIERARCHY FROM EHUB_PROD_RAW.cs90_master_mapping CMM INNER JOIN EHUB_PROD_RAW.wpd_spider_benefit_hierarchy WSBH ON CMM.HIERARCHY = WSBH.HIERARCHY INNER JOIN EHUB_PROD_RAW.legacy_bnft_cmpnt_xref LBCX ON CMM.BENEFIT = LBCX.BENEFIT_CMPNT_NM)
Same query runs fine from SQL Developer!
I am guessing something with hidden char or quotes.
Any guidance please.
You are selecting the same column twice:
( select
cmm.benefit,
( length(cmm.hierarchy) - length(replace(cmm.hierarchy,'>','') ) + 1 ) bnft_cmpnt_lvl_nbr,
lbcx.service_def_tgt_cd,
lbcx.service_def_desc,
lbcx.benefit_cmpnt_desc,
--lbcx.service_def_tgt_cd, <-- this one is duplicated
cmm.hierarchy
from
ehub_prod_raw.cs90_master_mapping cmm
inner join ehub_prod_raw.wpd_spider_benefit_hierarchy wsbh on cmm.hierarchy = wsbh.hierarchy
inner join ehub_prod_raw.legacy_bnft_cmpnt_xref lbcx on cmm.benefit = lbcx.benefit_cmpnt_nm
)
If you need it twice in the result set, then you should use aliases. I think SQL Developer will auto-alias it by appending a _1 to one of the ambiguous columns.

Error in Update JPA Query

I have a problem with this query when run is as follows
Query query = em.createQuery("UPDATE Equipo c JOIN c.histAsociados e SET e.horasTrabajadas = (CAST(c.horastd AS DECIMAL(18,2)) - (c.horastotales AS DECIMAL(18,2))) WHERE c.id=" + equipo.getId());
This is the exception that gets thrown when running
The SET identifier is missing from the UPDATE clause. [39, 39] The equal sign must be specified.[16, 38] The expression is invalid, which means it does not follow the JPQL grammar.[40, 43] The identification variable 'SET' cannot be a reserved word.[115, 115] The right parenthesis is missing from the sub-expression.[115, 115] The right parenthesis is missing from the sub-expression.[116, 126] The expression is invalid, which means it does not follow the JPQL grammar.[133, 151] The query contains a malformed ending.
Try something like this, putting it into a subquery, assuming that histAsociados is an entity inside Equipo entity:
Query query = em.createQuery("UPDATE Equipo c SET c.histAsociados WHERE c.histAsociados.id in(select Equipo.id from Equipo c1 LEFT JOIN c1.histAsociados e WHERE e.horasTrabajadas = (CAST(c1.horastd AS DECIMAL(18,2)) - (c1.horastotales AS DECIMAL(18,2))) AND c1.histAsociados.id = e.id) AND c.id=:id).setParameter("id", equipo.getId())
Also, could you please try putting some simple names to the attributes of entities. That increases readability.
According to the JPA specification, your syntax cannot be correct. The simplified form of the syntax for the UPDATEstatement can be stated as follows:
UPDATE <entity_name> <identification_variable> SET <identification_variable>.<state_field> = <value> WHERE <condition>
Applying this for your case it might look like:
"UPDATE HistAsociado?? e SET e.horasTrabajadas = (SELECT (CAST(c.horastd AS DECIMAL(18,2)) - CAST(c.horastotales AS DECIMAL(18,2))) AS DIFF FROM Equipo c WHERE c.id= " + equipo.getId())
In the above statement, I was guessing that HistAsociado could be an Entity name; otherwise you have to correct it!
The result of the subquery must also be a single value.
Warning: The modified statement would update all the records in the table as there is no WHERE condition is specified.
So, use this as a hint to solve the problem and don't use it before you have corrected the guessing and added the WHERE condition.
For more information and examples, you could read JPA update statement and this one too.

Categories