SQL query to find a class that contains minimum price - mysql

I have a table which contains different flight class names along with prices. Now my query result shows all of the results, flight names with corresponding classes and corresponding prices. Here is the query:
$sql = "SELECT f.dCity, f.aCity, f.date, f.flight_code, f.route, f.timeLeaving, f.timeLanding, f.price, f.class, i.airline_name ,
(SELECT location FROM iataairportcodes where iata_code='$fromm') as dLocation,
(SELECT airport_name FROM iataairportcodes where iata_code='$fromm') as dAirport,
(SELECT location FROM iataairportcodes where iata_code='$too') as aLocation,
(SELECT airport_name FROM iataairportcodes where iata_code='$too') as aAirport
FROM flights_test AS f, iataairlinescodes AS i
WHERE f.airline_code = i.iata_code
AND f.dCity = '$fromm'
AND f.aCity = '$too'
AND f.date='$newDate'";
But I want to find and display only that class, which contains minimum price; i.e., all data of that class only which contains minimum price.
(Forget about php variables please, those are from other sources)

Related

MySQL n-part Query for 1-n Relationship

(Just started learning SQL a few days ago so sorry if this is a stupid question!)
I have three tables, Users, Addresses, and AddressCategories. Each User has multiple Addresses, but no more than 1 Address per AddressCategory. I would like to make a single query that searches for Users based on different criteria for each AddressCategory.
Table structure looks like:
Users:
id
1
2
AddressCategories:
category
HomeAddress
WorkAddress
Addresses:
userId category address
1 HomeAddress 1 Washington Street
1 WorkAddress 53 Elm Avenue
2 HomeAddress 7 Bernard Street
Let's say I want to search for all users whose home address contains the word "Street" and work address contains the word "Avenue". I can use the query:
SELECT * FROM Users
INNER JOIN Addresses a1 ON Users.id=a1.userId
INNER JOIN Addresses a2 ON Users.id=a2.userId
WHERE a1.category='HomeAddress' AND a1.address LIKE '%Street%'
AND a2.category='WorkAddress' AND a2.address LIKE '%Avenue%'
If I want to query across an arbitrary number of AddressCategories, I can dynamically build a query using the same principle above:
// dictionary of query parts
var q_parts = {HomeAddress: 'Street',
WorkAddress: 'Avenue'
...}
// build the query string piece by piece
let q_str1="", q_str2="";
let i=0;
for (q in q_parts) {
i++;
q_str1 += "INNER JOIN Addresses a${i} ON Users.id=a${1}.userId ";
q_str2 += (i==1) ? "WHERE " : "AND ";
q_str2 += "a${i}.category='${q}' AND a${i}.address LIKE '%${q_parts[q]}%' ";
}
// complete query string
let q_str = "SELECT * FROM Users "+q_str1+q_str2;
The way I'm doing it now works, but it's easy to make a mistake building the query string and the final string quickly becomes enormous as the number of categories grows. Seems like there must be a better way. What is the right way to perform such queries in MySQL? (Or is there a problem with how I've organized my tables?)
You can use this one for query building.
Official site: https://knexjs.org/
Npm link: https://www.npmjs.com/package/knex
A sample SQL for don't have to join many times. It is not tested, and just an idea.
You can use When/then in Where clause for verifying case by case. And finally, filter base on the total categories of a User (group by).
SELECT *
FROM
Users Inner Join
(SELECT userId,
count(category) AS categoryCount
WHERE address LIKE '%Street%' LIKE CASE
WHEN category = 'HomeAddress' THEN '%Street%'
WHEN category = 'WorkAddress' THEN '%Avenue%'
END
GROUP BY userId) a ON Users.id = a.userId
WHERE categoryCount = ? -- inject your count of all categories here, maybe get from another query

Fetching the records by providing optional parameters in Spring

I need to fetch the records based on the optional parameters.
Ex Database: MySql
Tables:
Hotel-> hotel_id, name, group_id, status, brand_id, no_rooms, region_id
Region -> region_id, region_name, region_code, region_manager
Region to Hotel having one to many relationship.
I can fetch the hotel records using this type of query
Select * from MyDB.Hotel h where h.group_id = 2 and h.brand_id = "ABC" and h.status = "Available" and h.region_id in (select region_id from MyDB.Region r where r.region_code = "13" and r.region_name = "ABC");
Similarly I created an api endpoint to get the hotel details by passing group_id, brand_id, status, region_code, region_name as required parameters and able to fetch the records.
I am using Spring CRUD repository.
#Query(value="from Hotel h where (h.group =:group) and (h.brand = :brand) and (h.status = :status) and h.region in (from Region r where (r.regionCode =:regionCode) and (r.regionName =:regionName))")
Page<Hotels> findAllHotels (#Param("group") Group group,
#Param("brand") Brand brand,
#Param("status") String status,
#Param("regionCode") EnumProductGroup regionCode,
#Param("regionName") EnumProductType regionName,
Pageable pageable);
Now I need to send the request to same endpoint as optional parameters.
If one parameter is missing still needs to fetch the records based on other parametes. Means the missing parameters should removed from the where conditon dynamically.
I tried to pass the dynamic querystring to the repository query #Query but failed. I don't know is this possible.
request->controller->service->repository extends CrudRepository.
Is there anyway to generate dynamic query based on available parameters or is there any otherway which different than what I am trying.

Multiple SQL Selects to use values to further the search

I have a SQL query that gets a single row from the database. I want to ultimately return that row plus additional data that can be searched for with values from the first query's row. The only inital data I have is the magazineId. We will use 41659.
select productid, dispenserid from magazine where magazineid = 41659
Gives me two important data values to work with, in one row: ProductID and dispenserId...
Select MagazineID, dispenserId, ProductID from Magazine where ProductID = *** ProductID *** and dispenserId = ***dispenserId***
I ultimately want to get a new row(s), that is generated by doing searches that give me the data to work with in the first query.
How can one do this?
You could use subqueries:
SELECT MagazineID, DispenserID, ProductID
FROM Magazine
WHERE ProductID = (SELECT ProductID
FROM Magazine
WHERE MagazineID= 41659)
AND DispenserId = (SELECT DispenserID
FROM Magazine
WHERE MagazineID= 41659)
Though I'm not sure why you can't just do this:
SELECT MagazineID, DispenserID, ProductID
FROM Magazine
WHERE MagazineID = 41659
Keep in mind that the magazine with the given ID will certainly match by DispenserID and ProductID, so you can simply do this:
SELECT
M2.MagazineID,
M2.DispenserID,
M2.ProductID
FROM
Magazine M1
INNER JOIN Magazine M2 ON
M2.DispenserID = M1.DispenserID AND
M2.ProductID = M1.ProductID
WHERE
M1.MagazineID = 41659

Django left join query on multiple fields

I have defined three models that are as below
class City(models.Model):
city_name = models.CharField(...)
class Restaurant(models.Model):
restaurant_name = models.CharField(...)
city = models.ManyToManyFields(City)
class MenuItemCount(models.Model):
restaurant = models.ForeignKey(Restaurant)
city = models.ForeignKey(City)
menu_count = models.IntegerField()
One note is that all restaurants and cities might not exist in MenuCount. So a left join is needed.
I am trying to write the django query to retrieve a list of restaurant name, city name and menu counts. Example result would be
restaurant1, city1, 20
restaurant1, city2, None
restaurant2, city2, 30
restaurant3, city1, None
How can I write a query for this?
If you want to get all of the data in 1 query, you can use prefetch_related. You can see the documentation here. Here is the example.
City.objects.prefetch_related('restaurant_set', 'menuitemcount_set').all()

Linq Group on a multi-level object with select statement

I've got 3 dataset objects that are nested with each other using entity set objects. I am selecting the data like this
var newList = from s in MainTable
from a in s.SubTable1 where a.ColumnX = "value"
from b in a.Detail where b.Name = "searchValue"
select new {
ID = s.ID,
Company = a.CompanyName,
Name = b.Name,
Date = s.DueDate
Colour = b.Colour,
Town = a.Town
};
and this works fine, but the trouble is there are many records in the Detail object-list/table for each Name value so I get a load of duplicate rows and thus I only want to display one record per b.Name. I have tried putting
group s by b.Name into g
before the select, but then this seems to stop the select enabling me to select the columns I want (there are more, in practice). How do I use the group command in this circumstance while still keeping the output rows in a "flat" format?
Appending comment as answer to close question:-
Of course that if you group your results, you cant get select a column of a child, thats because there may be more than one childs and you have to specify an aggregate column for example the sum,max etx –