Retrieve data from two tables with indirect relation(from another table) - mysql

I have 3 tables
Division
id name
1 A
2 B
Region
Id name Divsion_id
01 Rim A
Territory
Id name region_id
001 a 01
002 b 01
003 c 01
Now I want to write a query such way that user will select division and its respective territories should get displayed.
How can I write this query, as
there is no direct relation between Divsion and Region?

select t.* from territory t
inner join region r on r.id = t.region_id
inner join devision d on d.name = r.division_id
where d.name = 'A'

Another approach would be to use IN operator with sub query. Inner query projects all regions having given region id and outer query looks for territories with selected regions. Though joins should perform better than nested query.
select * from territory where region_id in (select region_id from region where devision_id=<division id>)

Related

how can I get a mysql result set that contains both matched and unmatched records

I have the following tables:
suppliers
id name
1 s1
2 s2
3 s3
products
id name
1 ...
2 ...
.. ...
9 lemon
.. ...
and
product_suppliers
id supplier_id product_id
1 2 9
I need a result set that looks like the following one:
supplierName productSupplier
s1 null
s2 1
s3 null
I tried a left join like the following one:
select * from suppliers
left join product_suppliers on suppliers.id = product_suppliers.supplier_id
where product_suppliers.product_id = 9
but the result set contains just the lemon that is associated with the supplier s2 and I also need the rest of the suppliers for a future association.
thanks!
Just move the condition from the where clause to the on part of the left join. Conditions in the where clause are mandatory, so if a record has no match in product_suppliers it will evict it from the resultset.
select s.name supplier_name, ps.id product_supplier
from suppliers s
left join product_suppliers ps on s.id = ps.supplier_id and ps.product_id = 9
I also modified your query to implement a few best practices:
enumerate the columns in the SELECT clause
use table aliases
Remove the where condition, by doing that you are filtering just the product with id 9

MySQL join to get a single row using order/priority

I have a couple tables in MySQL DB
EID Name
1 Title A
2 Title B
3 Title C
LID EID Location Address Order
1 1 Office NY 1
2 1 Home IL 2
3 2 Office CA 1
4 3 Home NJ 2
I have the above 2 tables (Employee and Location). I would like to know the location of each Employee with office as a preferred choice and if 'office' does not exist then would need 'Home' location . The order column defined the order/priority of what is needed.
here is the output needed
EID LID Name Location Address
1 1 Title A Office NY
2 3 Title B Office CA
3 4 Title C Home NJ
The first join of the query below just connects the Employee and Location tables, but note that it results in all records from Location being joined. The critical part of the below query is the second INNER JOIN to a subquery. This subquery identifies the minimum (i.e. highest priority) order for each employee ID. This is then used to discard records from the first join which are not the highest priority.
SELECT t1.EID,
t2.LID,
t1.Name,
t2.Location,
t2.Address
FROM Employee t1
INNER JOIN Location t2
ON t1.EID = t2.EID
INNER JOIN
(
SELECT EID, MIN(`Order`) AS min_order
FROM Location
GROUP BY EID
) t3
ON t2.EID = t3.EID AND
t2.Order = t3.min_order
One other note: Don't name your columns Order, which is a MySQL keyword. To get my query to work, I had to put it in backticks, which is inconvenient to say the least, and possibly error prone.
Demo here:
SQLFiddle
There are two posibility to get your result.
1)If you need Based on Order result then use this query
SELECT e1.EID, l1.LID, e1.Name, l1.Location, l1.Address
FROM Employee e1
JOIN
(SELECT MIN(`Order `) as Minorder, EID, LID, Location, Address, Order
FROM Location l1
GROUP BY EID) l1
ON l1.EID = e1.EID AND l1.Minorder = l1.Order;
2)if you need result Based on EID then use this query
SELECT e1.EID,l1.LID,e1.Name,l1.Location,l1.Address
FROM Employee e1 JOIN
(SELECT MIN(`EID`)as Mineid,EID,LID,Location,Address,`Order` FROM Location l1 GROUP BY EID)l1
ON l1.Mineid = e1.EID;
Extra Note:-
Plese donot use mysql inbuilt keyword as Column name or Table name for more information read this link click here
You can the expected result by using inner join
Select a.eid,b.Lid,a.name,b.location,b.address from Table1 a innner join (select * from Tableb group by eid) b on
a.eid=b.eid;
you can try this code this will help you as i think
select E.EID,E.name,ad.LID,ad.LOCATION,ad.ADDRESS,ad.[order]
from #emp E inner join #address ad on E.EID = ad.EID
inner join (select EID, min([order]) [order]
from #address
group by EID) tt on ad.EID = tt.EIDand ad.[order] = tt.[order]

Free search on multiple tables using JOIN

I have a DB of Students who have a fullname, a location, and a list of schools they frequented.
"student" table
id | fullname | location
------------------------
"location" table
id | zipcode | city
-------------------
"school" table
id | name
---------
"student_school" table (which holds two foreign keys on school and user to create for each user a list of schools)
id | id_student | id_school
---------------------------
I want to perform a search through the students comparing the search term with student.fullname, location.zipcode, location.city, school.name and return all the students matching one (or more) of these conditions.
Note that student can have a null location, so we need an extern join.
Here is example of matching based on regular expressions:
SELECT distinct s.id, s.fullname
FROM student_school ss
JOIN student s ON s.id = ss.id_student
LEFT JOIN LOCATION l ON s.LOCATION = l.id
JOIN school sc ON ss.id_school = sc.id
WHERE (s.fullname RLIKE 'Sasha.*') or
(ifnull(l.zipcode RLIKE '100.*', 0)) or
(ifnull(l.city RLIKE 'New.*', 0)) or
(sc.name RLIKE '.*2')
And here is complete SQL fiddle
So the general idea is to join all student data, filter rows matching at least one criterion and use distinct to group data and avoid duplicating of results.
Update:
To include students with no school records you may use following FROM phrase:
student_school ss
RIGHT JOIN student s ON s.id = ss.id_student
LEFT JOIN LOCATION l ON s.LOCATION = l.id
LEFT JOIN school sc ON ss.id_school = sc.id

Selecting data from two tables using Mysql stored procedures

I have to select data from two tables with following criteria,
lets say there are two tables as,,
Table one
id | itemName | Quantity | companyName
1 bread 25 the Baker pvt ltd
2 butter 30 green famers
Table two
id | itemName | itemPrice
1 bread 30.50
6 jam 80.25
what I need is,
select items out of two tables which their ids are matching and the quantities of them should be multiplied by the unit price if ids are matching. The rows which don't have matching ids should be selected but their quantities should not multiplied.
SELECT o.id, o.itemName, o.companyName, o.Quantity * IFNULL(t.itemPrice, 1) total
FROM one o
LEFT JOIN two t
ON o.id = t.id
Something like this should work ...
Select a.id, a.itemName, a.companyName, a.Quantity * IFNULL(b.itemPrice,1) As total
From table1 as a
Left Join table2 as b on a.id = b.id

Proper formatting for this MYSQL query required

Struggling to get the correct MYSQL query assembled to do the following:
2 Tables (Locations and Venues).
In Locations I want to get the Unique location_name and location_id Where there is a venue with on_website = 1
This is to draw a drop down list for navigation.
So I have London as a location and in London I have several venues
In Wilmslow I have a location but there are not venues that I want to advertise (on_website = 0 on those)
Currently I get the output
Bath
London
Birmingham
London
Bristol
London
Where I would want
Bath
London
Birmingham
Tried this:
SELECT
tblLocations.location_name,
tblLocations.location_id,
tblVenues.venue_id
FROM
tblLocations
INNER JOIN tblVenues ON (tblLocations.location_id = tblVenues.location_id)
Where tblVenues.on_website = 1
And tried using distinct but It still gives me duplicate locations.
Any help would be great thanks
SELECT DISTINCT
tblLocations.location_name,
tblLocations.location_id
FROM
tblLocations
INNER JOIN tblVenues ON (tblLocations.location_id = tblVenues.location_id)
Where tblVenues.on_website = 1
You have to use distinct without the venue_id, because the venue_id is different for different rows in your query. Distinct only filters exactly matching rows.
If you'd listed all three selected columns, you'd saw that each of them are unique. That's how DISTINCT works. Just do not select fields you don't need.
GROUP BY could do the trick
SELECT
tblLocations.location_name,
tblLocations.location_id,
tblVenues.venue_id
FROM
tblLocations
INNER JOIN tblVenues ON (tblLocations.location_id = tblVenues.location_id)
Where tblVenues.on_website = 1
GROUP BY tblLocations.location_id