I am trying to insert into a table the results which I just selected from this query, But I can't figure it out.
List<Object[]> results = em.createQuery("SELECT s.competition_id, s.data, s.discipline, s.category, s.player_id,"
+ " s.playerFirstName, s.playerLastName, SUM(s.points) as points FROM Score s"
+ " GROUP BY s.competition_id, s.player_id "
+ " ORDER BY s.points DESC", Object[].class).getResultList();
This select is working, but I need to insert this into the result table.
You can use Insert Select statement into regular SQL. You just need to provide the same amount of compatible columns into the query. I think it should be possible with group by records as well.
You may use Insert Selects with my Daobab (http://www.daobab.io)
An example:
https://github.com/daobab-projects/daobab-100plus-examples/blob/main/src/main/java/io/daobab/demo/example/c_talented/InsertSelect.java
Related
I am working on converting a legacy MS access system to a spring-boot application and I came across a big query. I am mostly done with converting the functions from access to mysql but not able to understand how to convert the following DLookUp sub-query as a mySql subquery
DLookUp("[price]","tbl_so","[so_id] = " & tbl_trade.so_id & " AND [product_id] = " & tbl_po.product_id
What I understood is following won't work as I don't have the Inner Joins set between the 3 tables, tbl_so, tbl_po, tbl_trade
SELECT tbl_so.price FROM tbl_so WHERE tbl_so.so_id = tbl_trade.so_id AND tbl_so.product_id = tbl_po.product_id
My question is how do I know how the tables will join with each other in this case and also when this DLookUp query is seldom used. And also the solution for this query.
Well, as a general rule, dlookup() can be replaced with a left join. However, you can also use a sub-query and they tend to be "less" change to the query.
So, if we had this:
SELECT id, partNum, dlookup("PartDescrt","tblParts","PartID = " & partNum)
as Description from tblOrders.
You would replace the above dlookup() with a sub-query like this:
SELECT id, partNum,
(select PartDescrt from tblParts where tblParts.PartID = tblOrders.PartNum)
AS Description
from tblOrders
The above is SQL or access sql syntax, but quite sure the same should work for MySQL.
If there is more then one partNumber that matches the above, then add a TOP 1, and a order by with some unique row (PK ID column is best). So the query becomes:
(select TOP 1 PartDescrt from tblParts where tblParts.PartID = tblOrders.PartNum
ORDER BY PartDescrt, ID DESC)
AS Description
Team,
I have three tables.
myTransTable,myMasterTable 1, MymyMasterTable 2
myTransTable have a lot of entries 'Rank.No ' auto incerement field is to identify indvidual records . 'U.Name' holds user name. Each user can have multiple records in this table . But the most recent transaction of a user can be find by the max value for Rank.No after grouping by 'U.Name'
Once this max record i.e recent transaction is fetched their asociated data needs to fetched from other tables
How can this be done in most efficent way.
1.myTransTable(fields Rank.No(auto increment field),Name,RecNum,uname,date,type)
2.myMasterTable1 (RecNum,Recowner,recdate)
3.MymyMasterTable2 (uName,age ,address,contact num)
I tried these ways for selection the max record and fetch the assocated data from other tables
max records as a view and fetch data from other tables using normal query
Max records and associated data itself as a view and select data as needed
Which is best way to have minimum execution time?
My queries are which is the best way to find the max.
Option one
select a.`RecNum`,a.`Name`,a.`Date`, a.`type`"+
"from myTransTable a "+
"INNER JOIN "+
"(SELECT RecNumMAX(`Rank.No`) AS maxserialnum FROM myTransTable "+
"GROUP BY RecNumMAX)groupedRecNumMAX "+
" ON "+
" a.RecNum = groupedPWO.RecNum "+
"AND "+
"a.`Rank.No` = groupedRecNumMAX.maxserialnum "+
Option two
Select a.`RecNum`,a.`Name`,a.`Date`, a.`type`"+`
FROM from myTransTable a
WHERE s.`RecNum` in(select MAX(`RecNum`)
from myTransTable
group by RecNum)
This is just a suggestion adn is related to your first query .. that seems contain wrong reference to table and column name
looking to you code you should use a query like this
select a.`RecNum`
,a.`Name`
,a.`Date`
, a.`type`
from myTransTable a
INNER JOIN (
SELECT RecNum, MAX(`Rank.No`) AS maxserialnum
FROM myTransTable
GROUP BY RecNum
) g ON a.RecNum =g.RecNum AND a.`Rank.No` = g..maxserialnum
and this with proper index .. on RecNum, and Rank.No should be the most performant (you can check in explain plain and with proper execution test)
You should not use column name with dot separated name as Rank.No .. use Rank_No isteand and also for column name the is preferred lowercase not and not a mix of UpperOrLower case use underscore for separate the word instead
For starters, I'm a super novice in SQL, and so I don't have the knowledge to ask a straightforward question, but I'll do my best. Here is the query I'm trying to make:
query = conn1.prepareStatement(
"select Industry, Ticker, TransDate, min(TransDate), max(TransDate), " +
" count(distinct TransDate) as TradingDays, " +
" count(distinct Ticker) as TickerCnt, " +
" openPrice, closePrice " +
" from Company left outer join PriceVolume using(Ticker) " +
" group by Industry " +
" having TradingDays >= 150 " +
" order by Industry, Ticker, TransDate");
ResultSet rs = query.executeQuery();
Here's the Error:
SQLException: Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'reedy330.Company.Ticker' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
If I include Ticker and TransDate in the GROUP BY clause, the exception no longer happens, but the ResultSet is empty. What I'm trying to do is have a ResultSet with everything in the SELECT clause as elements. I built this query from a similar example query in the assignment description, which is why I don't understand it well.
Here is the layout of the database, table names bolded with a colon, keys are just in bold:
PriceVolume:
Ticker
TransDate
OpenPrice
HighPrice
LowPrice
ClosePrice
Volume
AdjustedGross
Company:
Ticker
Name
Industry
Location
Any ideas?
Is "sql_mode=only_full_group_by" necessary for you?
If not, change the sql_mode:
SET sql_mode = '';
OR
SET sql_mode = 'STRICT_ALL_TABLES';
When you're using group by, everything in your select clause must EITHER be an aggregate function (like min, max, count etc), OR be in the group by clause.
You need to include Ticker and TransDate in the group by clause.
I have a query which is taking more time to execute . I am trying to optimize it. There are functions in the GROUP BY which may be adding to the query time . So i am trying to figure out how to optimize that part.
I am using Mysql 5.5.17 .
I cannot use force index as i am using Hibernate, so that's out of option .
I have some other options like :
1) use the alias in place of concat(...) in group by.
2) or replace concat() with the the columns inside it .
Ex: group by concat(1,2,3.) => group by 1,2,3
After trying both the above options i dont see any difference in "Query Cost"
The query looks like this(table names changed) :
select sum(this_.a + this_.b + this_.c + this_.d + this_.e +
this_.f + this_.g + this_.h + this_.i + this_.j) as sent,
sum(this_.a + this_.b + this_.c + this_.d + this_.e) as delivered,
d2_.name as y2_, d2_.id as y3_, concat(cast(b4_.id as char),
'.',c1_.name,'.',cs5_.name,'_',date_format(b4_.createddate,
'%Y-%b-%d %H:%i:%s')
) as allias_concat, b4_.id as y5_,
this_.year as y6_, this_.month as y7_, this_.day as y8_,
this_.weekday as y9_, this_.weekofmonth as y10_,
this_.bltid as y11_,
b4_.id as y12_, c1_.name as y13_,
cs5_.name as y14_, b4_.createddate as y15_,
cs5_.subject as y16_, d2_.name as y17_
from TABLE1 this_
inner join TABLE2 c1_ on this_.cgnid=c1_.id
inner join TABLE3 b4_ on this_.bltid=b4_.id
inner join TABLE4 csc6_ on b4_.schdlid=csc6_.id
inner join TABLE5 cs5_ on this_.constid=cs5_.id
left outer join TABLE6 f3_ on this_.fid=f3_.id
inner join TABLE7 d2_ on this_.dptid=d2_.id
where (f3_.name<>'TRASH'
or c1_.fid=0
)
and c1_.status<>'K'
and d2_.id in (1)
and ((b4_.createddate between '2015-02-01 10:30:00'
AND '2015-05-13 10:29:59'
and csc6_.isrealtime = 'N'
)
or (csc6_.isrealtime = 'Y'
and this_.bltdate between '2015-02-01 10:30:00'
AND '2015-05-13 10:29:59')
)
group by d2_.id,
concat(cast(b4_.id as char),'.',c1_.name,'.',cs5_.name,'_',
date_format(b4_.createddate,'%Y-%b-%d %H:%i:%s')
),
b4_.id,
this_.year, this_.month, this_.day,
this_.bltid
limit 20001
Please suggest ...
Thanks In Advance ...
Sorry, but this is going to be an "anti-answer"...
It smells like "over-normalization". For example, it feels like b4_ is a normalization of a datetime (createddate) and nothing else. Is this correct? If so, that is adding complexity and slowing down both the WHERE and the GROUP BY, plus obliterating some optimization possibilities.
The "functions" are not the problem. Since the items in the GROUP BY are coming from different tables, there is no way to optimize it. The GROUP BY must gather the information from the various tables, put them in a temp table, sort it, then scan through it. (Or something like that. The point is that there is no shortcut.)
"I cannot use ... as i am using Hibernate" -- Yet another case where a 3rd party software "gets in the way". If you can't change the query, we can't help you.
I have the following code that returns me two nice tables (When using the SQL function in PhpMyAdmin). However, I am unable to insert them into my TABLE B.
How can I insert this in TABLE B rather than only showing it?
SELECT DateTimeCode, Rat,
MAX(IntendedStimulusDuration_ms) AS StimulusDuration,
SUM(Correct + Incorrect + Omission + PrematureNosepokes) AS total_trials,
SUM(Correct) AS correct,
SUM(Incorrect) AS incorrect,
SUM(Omission) AS omission,
SUM(PrematureNosepokes) AS premature,
SUM(PerseverativePanelPushes) AS P_PanelPushes,
SUM(PerseverativeNosepokes) AS P_nosepokes,
SUM(PerseverativeNosepokesSameHole) AS P_NPsame,
SUM(PerseverativeNOsepokesOtherHoles) AS P_NPother
FROM `FiveChoice_TrialData`
GROUP BY Rat,DateTimeCode;
--If correct = 1
SELECT DateTimeCode, Rat,
AVG(ResponseLatency_ms) AS ResponseLatency,
AVG(CollectionLatency_ms) AS CollectionLatency
FROM `FiveChoice_TrialData`
WHERE Correct = 1
GROUP BY Rat,DateTimeCode;
Basically I tried:
INSERT INTO TABLE_B (--all my col names, just like the alias stated above)
VALUE (--My two select statement as written above, separated by a coma)
You don't need the value statement when inserting from a query. Try this:
insert into table_b(<list of columns here>)
SELECT DateTimeCode, Rat,
MAX(IntendedStimulusDuration_ms) AS StimulusDuration,
SUM(Correct + Incorrect + Omission + PrematureNosepokes) AS total_trials,
SUM(Correct) AS correct,
SUM(Incorrect) AS incorrect,
SUM(Omission) AS omission,
SUM(PrematureNosepokes) AS premature,
SUM(PerseverativePanelPushes) AS P_PanelPushes,
SUM(PerseverativeNosepokes) AS P_nosepokes,
SUM(PerseverativeNosepokesSameHole) AS P_NPsame,
SUM(PerseverativeNOsepokesOtherHoles) AS P_NPother
FROM `FiveChoice_TrialData`
GROUP BY Rat,DateTimeCode;
And something similar for the second query.