How do I convert this SQL query into hibernate - mysql

Can someone please tell me how to convert this SQL query into hibernate?
SELECT * FROM sys_quote_master AS g1
INNER JOIN
(SELECT order_base_id, order_id FROM sys_quote_master
GROUP BY order_base_id, order_date_last_revised
ORDER BY order_date_last_revised desc) AS g2
ON g2.order_id = g1.order_id;
Basically,
I have tried this and it doesn't work:
DetachedCriteria crit1 = DetachedCriteria.forClass(QuoteMaster.class);
ProjectionList pList = Projections.projectionList();
pList.add(Projections.groupProperty("orderBaseId"));
session = HibernateSessionFactory.currentSession();
Criteria crit = session.createCriteria(QuoteMaster.class);
Criteria c = crit.createCriteria("QuoteMaster", CriteriaSpecification.INNER_JOIN);
c.setProjection(pList);
I get this error:
org.hibernate.QueryException: could not resolve property: this of:
QuoteMaster
And I think it has to do with this line of code were I am trying to create an inner join to the same table:
Criteria c = crit.createCriteria("QuoteMaster", CriteriaSpecification.INNER_JOIN);
So basically, my question is 'How to create a join to the same table using Criteria.createCriteria or Criteria.createAlias?' The doc for Criteria class states the first parameter is a dot-separated property path, but what the heck does that mean? :)
Every example I found so far shows how to do this with 2 or 3 tables but not to the same table and I have no idea what to use for the first argument.

I dont know how your entities are, this should give rough idea.
from SystQuoteMasterEntity sqm join ( select sqm1.orderbaseid, sqm1.orderId from SystQuoteMasterEntity sqm1 group by orderbaseid,orderdatelastrev order by orderdatelast desc) g2

Related

Inner join in combination with sum and group by

I am having some strange issue with the SQL statement below. The result groups by user IDs and some of them turn out right but for one of them (user ID = 1) the "initial_average" is multiplied by 3. I really have no idea why.. Is there something wrong with the structure of the statement? If it is not clear, the aim is to sum the field "initial_avg" in the "tasks" table and have it broken out by user. Some help with this is much appreciated. I am using MySQL.
SELECT sum(initial_avg) AS initial_average
, sum(initial_std) AS initial_standard_dev
, tasks.user
, hourly_rate
FROM tasks
INNER JOIN user_project
ON tasks.user=user_project.user
AND tasks.project=59
AND tasks.user=1
GROUP BY tasks.user
I just solved it by adding another "and" clause (AND user_project.project=59 )
Optimize your query (Try it):
SELECT SUM(initial_avg) AS initial_average, SUM(initial_std) AS initial_standard_dev, tasks.user, hourly_rate FROM tasks INNER JOIN user_project ON tasks.user = user_project.user AND tasks.project = User_project.project WHERE tasks.project = 59 AND tasks.user = 1 GROUP BY tasks.user, hourly_rate

Retrieving data from one table while comparing value from another table

Overview
I have two tables as can be seen below:
user_planes
----------------------------------
|id |user_id|plane_id|fuel|status|
----------------------------------
| 2 1 1 1 Ready |
----------------------------------
shop_planes
------------------------
|id |name|fuel_capacity|
------------------------
| 1 bob 3 |
------------------------
Foreign Key Primary Key
user_planes.plane_id <-> shop_planes.id
I want to be able to get every field (SELECT *) in user_planes and name and fuel_capacity based on the following criteria:
WHERE user_planes.user_id = ? - Parameter which will be added to the query through PHP.
WHERE user_planes.status = 'Ready'
WHERE user_planes.fuel < shop_planes.fuel_capacity
The Issue and My Attempts
I've tried JOIN however it retrieves data which doesn't fit that criteria, meaning it gets extra data which is from shop_planes and not user_planes.
SELECT * FROM `user_planes` WHERE fuel IN (SELECT shop_planes.fuel_capacity FROM shop_planes WHERE fuel < shop_planes.fuel_capacity) AND user_planes.user_id = 1 AND status = 'Ready'
and
SELECT * FROM `user_planes` INNER JOIN `shop_planes` ON user_planes.fuel < shop_planes.fuel_capacity AND user_planes.user_id = 1 AND user_planes.status = 'Ready'
I've searched Stackoverflow and looked through many questions but I've not been able to figure it.
I've looked up many tutorials but still can't get the desired result.
The desired result is that the query should use the data stored in user_planes to retrieve data from shop_planes while at the same time not getting any excess data from shop_planes.
Disclaimer
I really struggle using JOIN queries, I could use multiple separate queries however I wish to optimise my queries hence I'm trying to bring it in to one query.
If their isn't clarity in the question, please do say, I'll update it to the best of my ability.
Note - Is there an easy query builder option available either through phpmyadmin or an alternative software?
Thanks in advance.
Your last attempt was not a bad one, the only thing you missed there was the join criteria you described at the beginning of your post. I also moved the other filters to the where clause to better distinguish between join condition and the filters.
SELECT `user_planes`.*
FROM `user_planes`
INNER JOIN `shop_planes` ON user_planes.plane_id = shop_planes.id
WHERE user_planes.fuel < shop_planes.fuel_capacity AND user_planes.user_id = 1 AND user_planes.status = 'Ready'
First you need the base JOIN
SELECT up.* -- only user_plane fields
FROM shop_planes sp -- CREATE alias for table or field
JOIN user_planes up
ON sp.id = up.plane_id
Case 1: apply a filter in where condition with php parameter.
SELECT up.*
FROM shop_planes sp
JOIN user_planes up
ON sp.id = up.plane_id
WHERE up.user_id = ?
Case 2: apply a filter in where condition with string constant
SELECT up.*
FROM shop_planes sp
JOIN user_planes up
ON sp.id = up.plane_id
WHERE user_planes.status = 'Ready'
Case 3: aply filter comparing fields from both tables
SELECT up.*
FROM shop_planes sp
JOIN user_planes up
ON sp.id = up.plane_id
WHERE up.fuel < sp.fuel_capacity
Try something like:
SELECT
up.id AS User_Plane_ID
, up.[user_id]
, up.plane_id
, up.fuel
, up.[status]
, sp.name AS shop_Plane_Name
, sp.fuel_capacity AS shop_Plane_Fuel_Capacity
FROM User_Planes up
INNER JOIN Shop_Planes sp ON up.plane_id = sp.id
AND up.fuel < sp.Fuel_Capacity
WHERE up.[status] = 'Ready'
AND up.[user_id] = ?
Definitely find a tutorial for JOINs, and don't use SELECT *. With SELECT *, you may end up querying much more than you actually need and it can cause problems if the table changes. You'll enjoy your day much more if you explicitly name the columns you want in your query.
I've aliased some of the columns (with AS) since some of those column names may be reserved words. I've also moved the JOIN criteria to include a filter on fuel

Nested Select Statement Query with error "Incorrect syntax near the keyword 'GROUP' "

I have been through a few other posts relating to my error, but none of the solutions seem to work. I'm fairly new to SQL so sorry if its something really simple. I have two tables
Movie Inventory - which has columns movie_title, onhand_qty, and replacement_price
NotFlix - which has subscriber_name, queue_nbr, and movie_title
I am trying to join the two tables to output the total replacement price cost per customer, but when I do it gives me the error titled above. Here is my code, thanks in advance for any help!
SELECT subscriber_name, SUM (replacement_price) as replacement
FROM
(SELECT NotFlix.subscriber_name, NotFlix.movie_title, NotFlix.queue_nbr, MovieInventory.replacement_price
FROM NotFlix
INNER JOIN MovieInventory
ON NotFlix.movie_title = MovieInventory.movie_title
)
GROUP BY subscriber_name;
You are missing an alias:
SELECT AliasNameHere.subscriber_name, SUM (AliasNameHere.replacement_price) as replacement
FROM
(SELECT NotFlix.subscriber_name as subscriber_name, NotFlix.movie_title, NotFlix.queue_nbr, MovieInventory.replacement_price as replacement_price
FROM NotFlix
INNER JOIN MovieInventory
ON NotFlix.movie_title = MovieInventory.movie_title
) AliasNameHere
GROUP BY subscriber_name;
I Just don't get why are you doing a temporary table in FROM clause, you could just do a basic INNER JOIN here and potientialy avoid problem with alias name :
SELECT NotFlix.subscriber_name, SUM (MovieInventory.replacement_price) as replacement
FROM NotFlix
INNER JOIN MovieInventory
ON NotFlix.movie_title = MovieInventory.movie_title
GROUP BY subscriber_name;

MySQL error code 1064 syntax error

This is a very specific question to the kind of code i have written for postgresql and i am migrating to mysql for project requirements.
The code written so far in mysql is as follows :
(select substring(dt,1,9) as dt,concat(vish,visl,visn) as vis,ip
from assignment_walmart.b
where service='ss' and ua not like '%ktxn%'
and ua not like '%khte%'
and ua not like '%keynote%'
group by 1,2,3
) as A1
left join // This is where it shows the error.
(select ip,flag from
assignment_walmart.b1
group by 1,2
) as A2
on A1.ip=A2.ip
where A2.flag is NULL
group by 1,2;
The error is popping up near the naming of the two selected tables as "A1" and "A2", so i'm assuming it's not allowed in mysql.
Can you please help me with an alternate syntax for the above code as I have to use the two tables in this manner only to join in to get required results.
How exactly do i use alias or join 2 tables in such a manner which was clearly working in postgresql?
Any help would be appreciated.
You have a subquery joined to another query. This shouldn't work in either database. You need to wrap these in a select or something like that:
select A2.dt, A2.vis, count(*)
from (select substring(dt,1,9) as dt, concat(vish,visl,visn) as vis,ip
from assignment_walmart.b
where service='ss' and ua not like '%ktxn%'
and ua not like '%khte%'
and ua not like '%keynote%'
group by substring(dt,1,9), concat(vish,visl,visn), ip
) as A1 left join // This is where it shows the error.
(select ip,flag from
assignment_walmart.b1
group by ip, flag
) as A2
on A1.ip=A2.ip
where A2.flag is NULL
group by A2.dt, A2.vis;
I am making a guess on what you want for the outer query and what the aggregation fields are. It is a good idea to be explicit about which fields are being aggregated.
It looks like you are missing the SELECT ... FROM on the outer query.
It looks you mean for your query to be of the form:
SELECT ...
FROM ( inline view query ) A1
LEFT
JOIN ( inline view query ) A2
ON A1.col = A2.col ...
WHERE ...
GROUP BY ...

Correlated Subquery in a MySQL CASE Statement

Here is a brief explanation of what I'm trying to accomplish; my query follows below.
There are 4 tables and 1 view which are relevant for this particular query (sorry the names look messy, but they follow a strict convention that would make sense if you saw the full list):
Performances may have many Performers, and those associations are stored in PPerformer. Fans can have favorites, which are stored in Favorite_Performer. The _UpcomingPerformances view contains all the information needed to display a user-friendly list of upcoming performances.
My goal is to select all the data from _UpcomingPerformances, then include one additional column that specifies whether the given Performance has a Performer which the Fan added as their favorite. This involves selecting the list of Performers associated with the Performance, and also the list of Performers who are in Favorite_Performer for that Fan, and intersecting the two arrays to determine if anything is in common.
When I execute the below query, I get the error #1054 - Unknown column 'up.pID' in 'where clause'. I suspect it's somehow related to a misuse of Correlated Subqueries but as far as I can tell what I'm doing should work. It works when I replace up.pID (in the WHERE clause of t2) with a hard-coded number, and yes, pID is an existing column of _UpcomingPerformances.
Thanks for any help you can provide.
SELECT
up.*,
CASE
WHEN EXISTS (
SELECT * FROM (
SELECT RID FROM Favorite_Performer
WHERE FanID = 107
) t1
INNER JOIN
(
SELECT r.ID as RID
FROM PPerformer pr
JOIN Performer r ON r.ID = pr.Performer_ID
WHERE pr.Performance_ID = up.pID
) t2
ON t1.RID = t2.RID
)
THEN "yes"
ELSE "no"
END as pText
FROM
_UpcomingPerformances up
The problem is scope related. The nested Selects make the up table invisible inside the internal select. Try this:
SELECT
up.*,
CASE
WHEN EXISTS (
SELECT *
FROM Favorite_Performer fp
JOIN Performer r ON fp.RID = r.ID
JOIN PPerformer pr ON r.ID = pr.Performer_ID
WHERE fp.FanID = 107
AND pr.Performance_ID = up.pID
)
THEN 'yes'
ELSE 'no'
END as pText
FROM
_UpcomingPerformances up