Get Data from 5 tables - sql

i have 5 tables contains city information (Unite contain (but not always) sub unites - sub unites contain (but not always) building - and building contain (but not always) rooms
1-Unites: includes columns:
Id (PK)
UniteName
....
2- SubUnites: includes columns:
ID (PK)
Name
UniteId(FK for ID in Unites table Table)- Note (not all unite contain sub unite)
....
3- Building: includes columns:
ID (PK)
Name
SubUniteId (FK for ID in SubUnites Table)- Note (not all unite sub unite contain buildings)
...
4- Rooms: includes columns :
ID (PK)
Name
BuildingId (FK for ID in Building Table)- Note (not all building contain rooms)
....
5- Orders : includes columns:
ID
AreaId (which may be (ID column from Unite table) or (ID column from SubUnites table) or (ID column from Building table) or (ID column from Rooms table)
i can make order for for any of them by its ID
question :
how i can make sql select query to get orders for any of them with full information .. which mean if i get orders for a specif room i need to know in which building and in which sub unite and in which unite
and if i get orders for a specific building i need to know in which sub untes and in which unites an so on- with out duplicating data
i tried many queries but not working
any help

So it looks like you are trying to have a table [Orders] which is going to link/ relate to potentially 4 other tables via the [AreaId] column.
The problem is you haven't provided either a column to specify which table you are relating to for each particular order record.
Split the [Orders] table into 4 separate Orders tables with an order for each or provide a means, i.e. [UniteOrders], [SubUniteOrders], etc. Making each a one-unit to many orders relationship
Then if you want all orders, you could do a Union query to pull from all the tables
Another option would be to use GUIDs as the IDs and then you could store them in the [AreaId] and be certain to a high degree there would be no duplicates.
SQL Server doc on GUID type:
https://msdn.microsoft.com/en-us/library/ms187942.aspx

Ill give this a shot with out having access to the data. Please let me know if this is what you're trying to accomplish.
Select
U.ID
, U.NAME
, U.UniteName
, O_FROM_U.*
, SU.ID
, SU.NAME
, SU.UniteID
, O_FROM_SU.*
, B.ID
, B.Name
, B.SubUniteID
, O_FROM_B.*
, R.ID
, R.Name
, R.BuildingID
, O_FROM_R.*
FROM
Unites U
LEFT OUTER JOIN SubUnites SU ON SU.UNITEID = U.ID
LEFT OUTER JOIN Building B ON B.SubUniteID = SU.ID
LEFT OUTER JOIN Rooms R ON R.BuildingID = B.ID
LEFT OUTER JOIN ORDERS O_FROM_U ON U.ID = O_FROM_U.AreaID
LEFT OUTER JOIN ORDERS O_FROM_SU ON SU.ID = O_FROM_SU.AreaID
LEFT OUTER JOIN ORDERS O_FROM_B ON B.ID = O_FROM_B.AreaID
LEFT OUTER JOIN ORDERS O_FROM_R ON R.ID = O_FROM_R.AreaID

SELECT A.ID as unitid,A.Unitname as unitname,B.id as subuniteid,B.Name as subunitname,c.ID as buildingid,C.Name as buildingname,D.id as roomid,D.name as roomname,e.id as orderid,e.areaid
from
UniT A JOIN Subunit B
on A.Id=B.UnitId
Join Building c
on B.ID=C.Subunitid
Join Room D
ON C.ID=D.buildingid
Join Orders E
on E.Id=A.Id

Related

SQL Join between two tables excluding some fields

I have two tables Customer and Beneficiary, the relation between them is ManyToMany,
the generated table customers_beneficiaries contains the Id of Beneficiary and the Id of Customer
i want to get the list of customers with a given beneficiary_id
SELECT * from customer c
Full OUTER JOIN customers_beneficiaries cb
ON c.id= cb.customer_id
WHERE cb.beneficiary_id=8;
But the result iam getting contains the two fields of customers_beneficiaries table (customer_id && beneficiary_id)
How can i exclude them from the result
Thank you .
Try this:(In case you can change id column name in customer table to customer_id)
SELECT c.* from customer c
Full OUTER JOIN customers_beneficiaries cb
USING(customer_id)
WHERE cb.beneficiary_id=8;
USING Clause is like ON Clause which takes list of columns on which joining of table has to be done but those columns have to exist in both tables. The columns used in join operation appears only once in output.

SQLite select query if inner join query doesn't exists

I have two tables, one for all the foods which contains food id, default name and other foods values.
Another table is for the food name translations which contains food id, language id, translation.
What i want to do is join between these tables by the food id to get the translation for food id = 5 for example and language id = 1 which is Spanish for example. and i do it by:
SELECT *
FROM Foods
INNER JOIN FoodNameTranslations USING(Food_ID)
WHERE Food_ID = 5
AND Language_ID = 1
Now what if the the 'FoodNameTranslations' table doesn't have a translation for Food_ID 5 and Language 1?
then i want to simply get the food row with food id = 5 from the 'Foods' table (that contains the default name).
How can i make one query that does this? thanks!
You would do a LEFT JOIN and put the language ID into the join condition.
SELECT
COALESCE(t.TranslatedName, f.DefaultName) FoodName
FROM
Foods f
LEFT JOIN FoodNameTranslations t ON t.Food_ID = f.Food_ID AND t.Language_ID = 1
WHERE
f.Food_ID = 5
You cando do this by changing the JOIN condition:
INNER JOIN gets all records that are common between both tables based on the supplied ON clause.
LEFT JOIN gets all records from the LEFT linked and the related record from the right table ,but if you have selected some columns from the RIGHT table, if there is no related records, these columns will contain NULL.
RIGHT JOIN is like the above but gets all records in the RIGHT table.
FULL JOIN gets all records from both tables and puts NULL in the columns where related records do not exist in the opposite table.
Try using LEFT JOIN instead INNER JOIN, you query will be like this:
SELECT *
FROM Foods
LEFT JOIN FoodNameTranslations USING(Food_ID)
WHERE Food_ID = 5
AND Language_ID = 1

SQL LEFT JOIN multiple tables including link to 1 table for each join

For the sake of explaining my problem lets say I am building cars. In my DB a car is made out of parts (engine, chassis, wheel). Each part has a physical location (part_location from the table locations) which is linked via (part_location = location_id).
In my case, there will be only 1 of each part, each part is unique
In my query I am trying to assembly my cars in a query, including the city and country of each part (not the id)
The beginning of my query:
SELECT car_name, car_type, engine_name, engine_type, chassis_name, chassis_type, wheel_name, wheel_type
FROM cars
LEFT JOIN engines ON car_id = engine_car_id
LEFT JOIN chassis ON car_id = chassis_car_id
LEFT JOIN wheels ON car_id = wheel_car_id
How can I include the location of each part (e.g. car_city, car_country; an alias for each part from location_city, location_country)?
My tables are set up as follows:
Table cars
car_id
car_name
car_type
Table engines (same for chassis, wheels)
engine_id
engine_name
engine_type
engine_car_id
engine_location_id
Table locations
location_id
location_city
location_country
I think the idea behind your query is correct. You should write it with explicit aliases, so I would expect something like this:
SELECT c.car_name, c.car_type, e.engine_name, e.engine_type,
ch.chassis_name, ch.chassis_type,
w.wheel_name, w.wheel_type,
el.city as engine_city
FROM cars c LEFT JOIN
engines e
ON e.car_id = c.engine_id LEFT JOIN
chassis ch
ON ch.car_id = c.chassis_id LEFT JOIN
wheels w
ON w.wheel_car_id = c.car_id LEFT JOIN
locations el
ON el.location_id = e.location_id
However, without the table layouts or sample data, this is just a guess.

I want to retrieve data from 4 tables in SQL Server

I want to retrieve data from 4 tables. Patient table has id as PK which is the foreign key in other three tables ett, phar and ssc. Where a patient lie in only one category. i.e patient id pt1 exists in either of the 3 tables. now I want to retrieve patient info along with its associated category.
My query is:
SELECT *
FROM Patient p
INNER JOIN ETT t
ON p.Patient_ID = t.Patient_ID || INNER JOIN Pharmacological ph
ON p.Patient_ID = ph.Patient_ID
I used OR clause because I want only 1 inner join executing at one time. but its not giving me results, any suggestions??
....Patient table has ID as PK which is the foreign key in other three
tables name: ett, phar and ssc where a patient lie in only one
category. Example, patient id pt1 exists in either of the 3 tables.
Based on your statement, you can join all the tables in table Patient using LEFT JOIN since a record can only exist on one table. The query below uses COALESCE which returns the first non-null value with int the list.
The only thing you need is to manually specify the column names that you want to be shown on the list as shown below.
SELECT a.*,
COALESCE(t.colA, p.ColA, s.ColA) ColA,
COALESCE(t.colB, p.ColB, s.ColB) ColB,
COALESCE(t.colN, p.ColN, s.ColN) ColN
FROM Patient a
LEFT JOIN ETT t
ON a.Patient_ID = t.Patient_ID
LEFT JOIN Phar p
ON a.Patient_ID = p.Patient_ID
LEFT JOIN SSC s
ON a.Patient_ID = s.Patient_ID
To further gain more knowledge about joins, kindly visit the link below:
Visual Representation of SQL Joins
For or - do not ise ||, use "or"
You cannot join with or, you need re-format your query.

Join query from table with multiple foreign keys to same table primary key

I have a workorder system using SQL Express 2008. I have a table called Workorders that has several personnel that are linked to it via UserID. In the Workorder table I have TechID for the Technician, CustomerID for the Customer, QAID for quality assurance. These are linked back to the User Table via UserID (User Table PK). I want to join the tables to return Technician Name, Customer Name, and QA Name from the User Table and other job information information from the Workorder Table. I have no idea how to construct the join.
What about something a bit like this :
select tech.name as tech_name,
customer.name as customer_name,
qa.name as qa_name
from Workorders
inner join User as tech on tech.userId = Workorders.techId
inner join User as customer on customer.useId = Workorders.CustomerId
inner join User as qa on qa.useId = Workorders.QAID
(Might need some tunning, but the idea should be here)
ie, you are :
starting with a workorder
inner join on its tech guy (a User),
and then inner joinning on its customer (another user)
and so on
And this allows you to get each name, using the right alias in the select clause.
Note that I used aliases in the select clause too -- that might be usefull to have "worker_name" and "tech_name", instead of just two columns names "name" -- especially if you are calling this query from some other programming language.
Note : if one of those userId field can be NULL, you might want to use a left join, instead of an inner join.
select tus.Name as 'TechnicianName',
cus.Name as 'CustomerName',
qus.Name as 'QaName',
wod.*
from WorkOrders wod
left outer join
Users tus on tus.UserId = wod.TechId
left outer join
Users cus on cus.UserId = wod.CustomerId
left outer join
Users qus on qus.UserId = wod.QaId