join query with conditional check in sql - java

I'm trying to get some data from multiple tables using join query. I have a reservation table where I store the "pick-up location id" and "drop location id" and another table "location" where the location names were stored.
I'm trying to get the location name (pick-up and drop location) in 2 different variables from the "location" table with these 2 ids from the reservation table.
I have the tables with the following parameters.
Location table: "locations_deatils" has location_name location_id.
Reservation table: reservation_cars has pickup_location id, drop_location id, pick_up date, drop_date
SELECT l.location_name as pick-up_loc,
l.location_name as drop_loc,
c.pickup_date,
c.return_date,
FROM locations_deatils l inner join
reservation_cars c on l.locations_id = c.pickup_location and l.locations_id
= c.return_location
WHERE c.pickup_date >= :pickupTime and c.return_date <=:returnTime;

You need to do a separate join for the pick-up and for the drop location.
SELECT l1.location_name as 'pick-up location', l2.location_name as 'drop location', pickup_date, return_date
FROM reservation_cars r
JOIN locations_deatils l1 ON l1.locations_id = r.pickup_location
JOIN locations_deatils l2 ON l2.locations_id = r.return_location
WHERE r.pickup_date >= :pickupTime
AND r.drop_date <= :returnTime

Maybe you meant something like this:
SELECT p_loc.location_name AS pickup_location,
cars.pickup_date,
d_loc.location_name AS drop_location,
cars.return_date
FROM reservation_cars cars
JOIN location_details p_loc
ON cars.pickup_location = p_loc.location_id
JOIN location_details d_loc
ON cars.return_location = d_loc.location_id
WHERE .....
You might need to use an outer join in case the pickup and/or return locations are not set (yet).

Related

Inserting value in middle table in sqlite

I am trying to insert a value in a middle table, which is created by having two other tables relationship many to many. So this middle table has 2 foreign keys(idProduct and idWarehouse), one for each table and an additional row(storage). So I have trouble inserting in this third row.
It gives this error:
Result: near "SELECT": syntax error
At line 1:
INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage)
VALUES
(SELECT
This is my code:
INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage)
VALUES
(SELECT id FROM Products
WHERE nameProduct = 'cheese',
SELECT id FROM Warehouse
WHERE nameWarehouse = 'Vegas',
'10')
Each of the queries must be enclosed inside parantheses:
INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage) VALUES
(
(SELECT id FROM Products WHERE nameProduct = 'cheese'),
(SELECT id FROM Warehouse WHERE nameWarehouse = 'Vegas'),
'10'
);
This will work if theses queries return always only 1 row, so both columns nameProduct and nameWarehouse must be unique.
The statement can also be written without the VALUES clause, with SELECT:
INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage)
SELECT
(SELECT id FROM Products WHERE nameProduct = 'cheese'),
(SELECT id FROM Warehouse WHERE nameWarehouse = 'Vegas'),
'10';

How to retrieve data and count of data at same time in hql?

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)

remove duplicate Data after Execute SelectQuery in mutliple Tables

i have Three tables [users,projects,scenarios] i need to get latest update projects details based on modified Date column with out duplicate values
the tables are:
users Table :
project table
scenario Table
and i try below query but its return duplicates values if am using group by then old values came but i need latest values
With out Group by query
SELECT
p.`PROJECT_NAME`,
p.`CREATED_DATE`,
s.`MODIFIED_DATE`
FROM
`projects` p
JOIN `scenarios` s ON
s.`PROJECT_ID` = p.`PROJECT_ID`
WHERE
P.`USER_ID` =(
SELECT
USER_ID
FROM
users
WHERE
EMAIL = 'test#gmail.com'
)
ORDER BY
s.`MODIFIED_DATE`
DESC
out put:
with Group by Query :
SELECT
p.`PROJECT_NAME`,
p.`CREATED_DATE`,
s.`MODIFIED_DATE`
FROM
`projects` p
JOIN `scenarios` s ON
s.`PROJECT_ID` = p.`PROJECT_ID`
WHERE
P.`USER_ID` =(
SELECT
USER_ID
FROM
users
WHERE
EMAIL = 'test#gmail.com'
)
group by p.PROJECT_NAME
ORDER BY
s.`MODIFIED_DATE`
DESC
output:
You can separately get the latest scenario per project using a subquery then the resulting rows will then be join again to get the other columns, if needed.
SELECT p.PROJECT_NAME,
p.CREATED_DATE,
s.MODIFIED_DATE
-- all columns in s.* will have the latest row
FROM projects p
INNER JOIN scenarios s
ON p.PROJECT_ID = s.PROJECT_ID
INNER JOIN
(
SELECT project_ID, MAX(modified_date) MAX_modified_date
FROM scenarios
GROUP BY project_ID
) t ON s.project_ID = t.project_ID
AND s.modified_date = t.MAX_modified_date
INNER JOIN users u
ON P.USER_ID = u.USER_ID
WHERE u.EMAIL = 'test#gmail.com'
ORDER BY s.MODIFIED_DATE DESC
However, if you don't need to get the other columns, you can directly use MAX() and GROUP BY.
SELECT p.PROJECT_NAME,
p.CREATED_DATE,
MAX(s.MODIFIED_DATE) AS MAX_MODIFIED_DATE
FROM projects p
INNER JOIN scenarios s
ON p.PROJECT_ID = s.PROJECT_ID
INNER JOIN users u
ON P.USER_ID = u.USER_ID
WHERE u.EMAIL = 'test#gmail.com'
GROUP BY p.PROJECT_NAME,
p.CREATED_DATE
ORDER BY MAX_MODIFIED_DATE DESC

How to create mapping of composed object with Hibernate when using a complex sqlquery?

I am trying to use the below query with Hibernate's session.createSQLQuery.
The Entity object corresponding to user has an attribute called address.
The address object is created out of 5 fields from table 'user'.
If I do not use an SQLQuery it gets filled auto-magically.
However without the SQLQuery I can't get all the info I would get from the desired joins shown below.
The user entity object also attributes like accessPlan which I am filling up using
.addEntity("accessPlan", AccessPlan.class)
Query:
SELECT
user.*,
ap.*,
country.*,
auth.*,
GROUP_CONCAT(coup.code SEPARATOR ' ') coupons
FROM
user
INNER JOIN access_plan ap ON (user.access_plan = ap.id)
INNER JOIN country ON (user.country=country.code)
LEFT JOIN user_auth auth ON (user.id = auth.userid)
LEFT JOIN (
SELECT
trans.user_id,coupon.code
FROM
payments_transaction AS trans
INNER JOIN payments_coupon coupon ON (trans.payments_coupon_id=coupon.id)
) coup ON (user.id=coup.user_id)
GROUP BY user.id;
What can be the easiest way to fill up the composed address object while using the SQLQuery?
OR
Is there a way to avoid using SQLQuery for a query like this?
Please check below example from the section 'Returning multiple entities'
String sql = "SELECT ID as {c.id}, NAME as {c.name}, " +
"BIRTHDATE as {c.birthDate}, MOTHER_ID as {c.mother}, {mother.*} " +
"FROM CAT_LOG c, CAT_LOG m WHERE {c.mother} = c.ID";
List loggedCats = sess.createSQLQuery(sql)
.addEntity("cat", Cat.class)
.addEntity("mother", Cat.class).list()
In your case, cat = user, mother = address... somewhat like that.
I do not have anything to try out at the moment but I guess this will help.

Java Query for retrieving records not in the foreign key table

Hi i want to have a query to retrieve records which is not in the another table. For eg.(List all the room Number which is unoccupied at singapore hotel).
Room Hotel Booking
-------- -------------- ------------------
room_no hotel_no hotel_no
hotel_no hotel_name room_no
date_from
date_to
is there any way to retrieve this record with just one sql query?
You can try this query
select room_no
from room
where room_no not in
(select room_no
from Booking
where hotel_no = singapore_hotel_no)
Select room.roon_num
from Room left outer join Hotel on room.room_no = hotel.room_no
left outer join Booking on room.room_no = booking.room_no and hotel.hotel_no = booking.hotel_no
where hotel.hotel_name = ?
and not (? between (booking.date_from , booking.date_to))
here first ? is 'singapore hotel'
and second ? is date for which you want to query

Categories

Resources