hibernate access outer query field in subquery - mysql

I have the below query which works in Mysql Workbench but get an error in hibernate
insert into namingsequences(currentseq, namingtype, scope, sequencekey, startrange, endrange, steprange, rangeactive)
select (a.currentseq + 5) as currentseq, namingtype, scope, sequencekey, startrange, endrange, steprange, rangeactive from namingsequences a
where a.sequencekey = 'test1123' and a.namingtype = 'test' and a.scope = 'test'
and a.currentseq >= a.startrange and a.currentseq <= a.endrange and not exists
(select 1 from namingsequences b where b.sequencekey = 'test1123' and b.namingtype = 'test'
and b.currentseq >= b.startrange and b.currentseq <= b.endrange
and b.scope = 'test' and b.currentseq = (a.currentseq+5) )
order by currentseq ;
insert into NamingSequences ( namingtype, scope, sequencekey,startrange,
endrange, steprange, currentseq, rangeactive )
select namingsequ0_.namingtype as col_0_0_, namingsequ0_.scope as col_1_0_,
namingsequ0_.sequencekey as col_2_0_, namingsequ0_.startrange as col_3_0_,
namingsequ0_.endrange as col_4_0_, namingsequ0_.steprange as col_5_0_,
namingsequ0_.currentseq+? as col_6_0_, namingsequ0_.rangeactive as col_7_0_ from NamingSequences namingsequ0_
where namingsequ0_.sequencekey=? and namingsequ0_.namingtype=? and namingsequ0_.scope=?
and namingsequ0_.currentseq>=namingsequ0_.startrange and namingsequ0_.currentseq<=namingsequ0_.endrange
and not (exists (select 1 from NamingSequences namingsequ1_ where
namingsequ1_.sequencekey=? and namingsequ1_.namingtype=?
and namingsequ1_.currentseq>=namingsequ1_.startrange
and namingsequ1_.currentseq<=namingsequ1_.endrange
and namingsequ1_.scope=? and
namingsequ1_.currentseq=NamingSequences.currentseq+?))
order by namingsequ0_.currentseq
[DEV: 2018-Feb-28 16:32:47,884][WARN ][http-nio-8082-exec-35]SQL Error: 1054, SQLState: 42S22
[DEV: 2018-Feb-28 16:32:47,884][ERROR]http-nio-8082-exec-35 Unknown column 'NamingSequences.currentseq' in 'where clause'
It seems that it cannot access the outer query field from the subquery. The error seems to be from the hibernate query penultimate line.
Also, can i restrict that only one row will be returned by select and inserted?
Query hbquery = session.createQuery(queryString);
hbquery.setMaxResults(1);
hbquery.setParameter("scope", scope);
hbquery.setLong("increment", step);
hbquery.setParameter("nameType", namingType);
hbquery.setParameter("seqKey", seqKey);
int ret = hbquery.executeUpdate();

Related

LINQ MY SQL QUERY "BIGINT UNSIGNED value is out of range in"

I've got a strange situation.
I've got a column (smallint) that has a single value of 6
I run using a linq to retrieve records that are Validity_months old.
var query = db.table_1
.AsNoTracking()
.Include(b => b.table_2)
.ThenInclude(t => t.table_3)
.Where(e => e.Date <= DateTime.UtcNow.AddMonths(e.table_2.ValidityMonths))
.Where(e => e.Date >= DateTime.UtcNow.AddMonths(e.table_2.ValidityMonths*-1)));
This throws an MySQL Error
Error Code: 1690. BIGINT UNSIGNED value is out of range in '(database.s0.validity_months * (-(1)))'
The query above translates into SQL Query
SELECT *
FROM `table_1` AS `s`
LEFT JOIN `table_2` AS `s0` ON `s`.`table_2_id` = `s0`.`id`
LEFT JOIN `table_3` AS `s1` ON `s0`.`table_3_id` = `s1`.`id`
WHERE (`s`.`date` <= DATE_ADD(UTC_TIMESTAMP(), INTERVAL CAST(`s0`.`validity_months` AS signed) month)))
AND (`s`.`date` >= DATE_ADD(UTC_TIMESTAMP(), INTERVAL CAST(`s0`.`validity_months` * -1 AS signed) month));
This ran into MySQL throws the same error. The problem is at
CAST(`s0`.`validity_months` * -1 AS signed)
How do I negate a field in LINQ. This feels like it's a EFCore bug, but I am not sure yet.

MySQL error MySQL # 1415 on Trigger creation

I am trying to create a trigger using PHPMyadmin GUI, but encountered an error MySQL # 1415. Here is my query for the trigger.
SELECT *
FROM `manage_order` O
INNER JOIN `manage_transaction` T ON T.txn_id = O.trans_id
WHERE O.`trans_status` = 'Completed' && O.`order_via` = 'Bid' && O.`release_flag` = 'Y'
ORDER BY O.`added_date` DESC;
INSERT INTO `manage_site_income_details`
VALUES (NULL, T.t_id, T.about, O.order_id, O.order_amt * 0.035, NOW());

Is there a way to pass an alias column name in a nested sub-query, via WHERE IN statement, to the UPDATE statement?

I came across this -
Using ALIAS column in WHERE recently and I understand why the WHERE clause is giving me an error but I can't seem to figure out any other way to write my nested query. The SELECT sub-query runs completely fine by itself.
The error is as follows:
Error Code: 1054. Unknown column 'actual_start_time' in 'IN/ALL/ANY subquery'
Table Structure:
Students: student_id student_name login_time logout_time
Tests: test_id test_start_time test_end_time
TestStats: test_id student_id test_duration
UPDATE test_stats
SET test_duration = datediff(hour, actual_start_time - actual_end_time)
WHERE (actual_start_time, actual_end_time)
IN (
SELECT
CASE
WHEN (s.login_time > t.test_start_time) THEN s.login_time
ELSE t.test_start_time
END AS actual_start_time,
CASE
WHEN (s.logout_time < t.test_end_time) THEN s.logout_time
ELSE t.test_end_time
END AS actual_end_time
FROM tests AS t, students AS s, test_stats AS ts
WHERE t.test_id = ts.test_id and s.student_id = ts.student_id);
This appears to be what you want:
UPDATE test_stats ts JOIN
tests t
ON t.test_id = ts.test_id JOIN
students s
ON s.student_id = ts.student_id
SET test_duration = timestampdiff(hour,
GREATEST(s.login_time, t.test_start_time),
LEAST(s.logout_time, t.test_end_time)
);

Error in hive query Invalid table alias

This is my hive query
INSERT OVERWRITE TABLE bts_monthly_points_liability_rollforward
SELECT currMonth.businessEventType,
prevMonth.totalFaceValue,
prevMonth.totalAccountingValue,
currMonth.earnedFaceValue,
currMonth.earnedAccountingValue,
currMonth.expiredFaceValue,
currMonth.expiredAccountingValue,
currMonth.earnedPointsReturnFaceValue,
currMonth.earnedPointsReturnAccountingValue,
currMonth.spendPointsFaceValue,
currMonth.spendPointsAccountingValue,
currMonth.spendPointsReturnFaceValue,
currMonth.spendPointsReturnAccountingValue,
currMonth.adjustmentFaceValue,
currMonth.adjustmentAccountingValue,
currMonth.totalFaceValue,
currMonth.totalAccountingValue
FROM
(
SELECT business_event_type AS businessEventType,
SUM(earned_face_value) AS earnedFaceValue,
SUM(earned_accounting_value) AS earnedAccountingValue,
SUM(expired_face_value) AS expiredFaceValue,
SUM(expired_accounting_value) AS expiredAccountingValue,
SUM(earned_return_face_value) AS earnedPointsReturnFaceValue,
SUM(earned_return_accounting_value) AS earnedPointsReturnAccountingValue,
SUM(spend_face_value) AS spendPointsFaceValue,
SUM(spend_accounting_value) AS spendPointsAccountingValue,
SUM(spend_return_face_value) AS spendPointsReturnFaceValue,
SUM(spend_return_accounting_value) spendPointsReturnAccountingValue,
CAST(0 AS BIGINT) AS adjustmentFaceValue,
CAST(0 AS BIGINT) AS adjustmentAccountingValue,
(SUM(earned_face_value)+SUM(expired_face_value)+SUM(earned_return_face_value)+SUM(spend_face_value)+SUM(spend_return_face_value)) AS totalFaceValue,
(SUM(earned_accounting_value)+SUM(expired_accounting_value)+SUM(earned_return_accounting_value)+SUM(spend_accounting_value)+SUM(currMonth.spend_return_accounting_value)) AS totalAccountingValue
FROM ${pointsApplicationName}_points_balance
WHERE unix_timestamp(accounting_date,'yyyy-MM-dd') >= unix_timestamp("${startDate}",'yyyy-MM-dd') AND unix_timestamp(accounting_date,'yyyy-MM-dd') < unix_timestamp("${endDate}",'yyyy-MM-dd')
GROUP BY business_event_type
)currMonth
JOIN
(
SELECT business_event_type AS businessEventType,
(SUM(earned_face_value)+SUM(expired_face_value)+SUM(earned_return_face_value)+SUM(spend_face_value)+SUM(spend_return_face_value)) AS totalFaceValue,
(SUM(earned_accounting_value)+SUM(expired_accounting_value)+SUM(earned_return_accounting_value)+SUM(spend_accounting_value)+SUM(spend_return_accounting_value)) AS totalAccountingValue
FROM ${pointsApplicationName}_points_balance
WHERE unix_timestamp(accounting_date,'yyyy-MM-dd') >= unix_timestamp("${previousMonthStartDate}",'yyyy-MM-dd') AND unix_timestamp(accounting_date,'yyyy-MM-dd') < unix_timestamp("${startDate}",'yyyy-MM-dd')
GROUP BY business_event_type
)prevMonth
ON prevMonth.businessEventType = currMonth.businessEventType;
Error that I am receiving after running this query:
SemanticException [Error 10004]: Line 38:129 Invalid table alias or column reference 'currMonth': (possible column names are: business_event_type, accounting_date, earned_face_value, earned_accounting_value, expired_face_value, expired_accounting_value, earned_return_face_value, earned_return_accounting_value, spend_face_value, spend_accounting_value, spend_return_face_value, spend_return_accounting_value)
Command exiting with ret '255'
The problem is the line 35 of your query. Here's how the query works:
SELECT ...
FROM (
SELECT business_event_type AS businessEventType,
...
(SUM(earned_accounting_value)+SUM(expired_accounting_value)+SUM(earned_return_accounting_value)+SUM(spend_accounting_value)+SUM(currMonth.spend_return_accounting_value)) AS totalAccountingValue
FROM ${pointsApplicationName}_points_balance
...
)currMonth
JOIN (...)prevMonth
ON prevMonth.businessEventType = currMonth.businessEventType;
Here you can see that you are using currMonth alias inside of the subquery that aliased as currMonth. The alias does not exist in this context, this is why you get an error. It should be like this:
(SUM(earned_accounting_value)+SUM(expired_accounting_value)+SUM(earned_return_accounting_value)+SUM(spend_accounting_value)+SUM(spend_return_accounting_value)) AS totalAccountingValue

Error creating a SP with temporal table inside and subquery

I've created this temporal table in my store procedure, as you can see I have more than 1 records for the same ID:
#tmpTableResults
TmpInstallerID TmpConfirmDate TmpConfirmLocalTime
============== ============== ===================
173 2011-11-08 11:45:50
278 2011-11-04 09:06:26
321 2011-11-08 13:21:35
321 2011-11-08 11:44:54
483 2011-11-08 11:32:00
483 2011-11-08 11:31:59
645 2011-11-04 10:03:15
645 2011-11-04 07:03:15
That is the result of the query to create #tmpTableResults
DECLARE #tmpTableResults TABLE
(
TmpInstallerID int,
TmpConfirmDate date,
TmpConfirmLocalTime time
)
DECLARE #tmpTableQuery VarChar(800)
SET #tmpTableQuery = 'select FxWorkorder.INSTALLERSYSID, FxWorkorder.CONFIRMDATE, FxWorkorder.CONFIRMLOCALTIME from FxWorkorder
join install on FxWorkorder.INSTALLERSYSID = install.sysid
join RouteGroupWorkarea on FxWorkorder.WORKAREAGROUPSYSID = RouteGroupWorkarea.IWORKAREA_ID
join RoutingGroup on RouteGroupWorkarea.IRG_ID = RoutingGroup.IRG_IDENTITY
where FxWorkorder.SCHEDULEDDATE > = #StartDate and FxWorkorder.SCHEDULEDDATE <= #EndDate
and FxWorkorder.Jobstatus <> "Unassign"
and FxWorkorder.Jobstatus <> "Route"
and install.FOXTELCODE <> ""
and FxWorkorder.CONFIRMLOCALTIME is not null
and FxWorkorder.CONFIRMDATE <> ""
group by FxWorkorder.INSTALLERSYSID, FxWorkorder.CONFIRMDATE, FxWorkorder.CONFIRMLOCALTIME
order by FxWorkorder.INSTALLERSYSID, FxWorkorder.CONFIRMDATE, FxWorkorder.CONFIRMLOCALTIME desc '
INSERT INTO #tmpTableResults EXEC(#tmpTableQuery)
I'm creating another query to get data from another table and only the first record from the temporal table for the same INSTALLERSYSID
SELECT RoutingGroup.SDESCRIPTION, FxWorkorder.INSTALLERSYSID, FxWorkOrder.JOBSTATUS, Install.FOXTELCODE,
install.NAME, FxWorkOrder.ScheduledDate,
count(*) as TotalJobs, COUNT(CONFIRMDATE) as ConfirmedJobs,
(select TmpInstallerID, TmpConfirmDate, TmpConfirmLocalTime from #tmpTableResults where TmpInstallerID = FxWorkorder.INSTALLERSYSID)
from FxWorkorder
join install on fxworkorder.INSTALLERSYSID = install.sysid
join RouteGroupWorkarea on FxWorkOrder.WORKAREAGROUPSYSID = RouteGroupWorkarea.IWORKAREA_ID
join RoutingGroup on RouteGroupWorkarea.IRG_ID = RoutingGroup.IRG_IDENTITY
where FxWorkorder.SCHEDULEDDATE > = #StartDate and FxWorkorder.SCHEDULEDDATE <= #EndDate
and FxWorkOrder.Jobstatus <> 'Unassign'
and FxWorkOrder.Jobstatus <> 'Route'
and Install.FOXTELCODE <> ''
group by RoutingGroup.SDESCRIPTION,FxWorkOrder.INSTALLERSYSID, FxWorkOrder.JOBSTATUS, Install.FOXTELCODE,install.NAME, FxWorkOrder.ScheduledDate,FxWorkOrder.WORKAREAGROUPSYSID
When I tried to save the sp I got the error
"Only one expression can be specified in the select list when the subquery is not introduced with EXISTS."
I can't see why I got this error. But if I run the query in sql that works. Can someone see the error?
I don't know how your second query works for you ‘in sql’ (where is that supposed to be? do you mean SSMS = SQL Server Management Studio?), but I'm sure it cannot possibly work in any version of SQL Server that exists at the moment. It's because of this subquery in the SELECT list:
(select TmpInstallerID, TmpConfirmDate, TmpConfirmLocalTime from #tmpTableResults where TmpInstallerID = FxWorkorder.INSTALLERSYSID)
The thing is, every expression in the SELECT clause should be scalar, but this subquery returns a row of more than one value. Even if it's only one row, it is illegal there, because it returns several columns. The subquery in that context should return no more than one value, i.e. it should be one column and the result produced should contain either no rows or just one.
You could try this query instead (although I'm not entirely sure without knowing more details about your schema):
SELECT
RoutingGroup.SDESCRIPTION,
FxWorkorder.INSTALLERSYSID,
FxWorkOrder.JOBSTATUS,
Install.FOXTELCODE,
install.NAME, FxWorkOrder.ScheduledDate,
count(*) as TotalJobs, COUNT(CONFIRMDATE) as ConfirmedJobs,
tmp.TmpInstallerID,
tmp.TmpConfirmDate,
tmp.TmpConfirmLocalTime
from FxWorkorder
join install on fxworkorder.INSTALLERSYSID = install.sysid
join RouteGroupWorkarea on FxWorkOrder.WORKAREAGROUPSYSID = RouteGroupWorkarea.IWORKAREA_ID
join RoutingGroup on RouteGroupWorkarea.IRG_ID = RoutingGroup.IRG_IDENTITY
join #tmpTableResults tmp ON tmp.TmpInstallerID = FxWorkorder.INSTALLERSYSID
where FxWorkorder.SCHEDULEDDATE > = #StartDate
and FxWorkorder.SCHEDULEDDATE <= #EndDate
and FxWorkOrder.Jobstatus <> 'Unassign'
and FxWorkOrder.Jobstatus <> 'Route'
and Install.FOXTELCODE <> ''
group by
RoutingGroup.SDESCRIPTION,
FxWorkOrder.INSTALLERSYSID,
FxWorkOrder.JOBSTATUS,
Install.FOXTELCODE,install.NAME,
FxWorkOrder.ScheduledDate,
FxWorkOrder.WORKAREAGROUPSYSID
tmp.TmpInstallerID,
tmp.TmpConfirmDate,
tmp.TmpConfirmLocalTime
That is, I added one more join, the one to #tmpTableResults, as well as added the columns you were trying to pull to the SELECT clause and to the GROUP BY clause.
Also, if I were you I would consider using short aliases for tables, like this:
SELECT
…
wo.INSTALLERSYSID,
wo.JOBSTATUS,
…
from FxWorkorder wo
join …
That might make your queries more readable.