简体   繁体   中英

Join 4 Tables in SQL with left join and inner join

Hey I am trying to join 4 tables in sql, with an left join and an inner join.

Hospital table

HospitalID| Name| Province| Email| 

Order table

OrderID| HospitalID| StaffID| DeliverID| Date| Time

Item table

ItemID| Type| Name| Quantity| Expiry_Date

OrderItem table

OrderItemID| OrderID| ItemID| Quantity

I attempted executing the following SQL query but I am getting error message and I don't know what I'm doing wrong.

SELECT Hospital.Name, Item.Type, OrderItem.Quantity
FROM Hospital 
LEFT JOIN [Order]   
ON Hospital.HospitalID=[Order].HospitalID
INNER JOIN (SELECT Item.Type 
            FROM Item 
            GROUP BY Item.Type)
OrderItem ON Item.ItemID = OrderItem.ItemID
; 

There are few mistakes in the query, the syntax using [Order] is invalid in mysql, and then you need an alias for the inner query. Also OrderItem needs to be joined first with Order. Further more no need to use use subquery for join since you are not doing any aggregate part to get the data from Item . In mysql the query will look like below.

SELECT 
h.Name, 
i.Type, 
oi.Quantity
FROM Hospital h 
LEFT JOIN `Order` o  ON o.HospitalID = h.HospitalID
INNER JOIN OrderItem oi on oi.OrderID = o.OrderID
INNER JOIN Item i 
on i.ItemID = oi.ItemID ; 

Note that Order is a reserved word so you need to backtick it as done in the query above

you can use below simple query-

SELECT 
hosp.Name, 
itm.Type, 
oi.Quantity
FROM Hospital hosp 
JOIN `Order` ord  ON ord.HospitalID = hosp.HospitalID
JOIN OrderItem oi on oi.OrderID = ord.OrderID
JOIN Item itm on itm.ItemID = oi.ItemID; 

If there is chance that you want to show all hospital name even without its details in other tables like type, quantity etc. then you can use of left join-

SELECT 
hosp.Name, 
itm.Type, 
oi.Quantity
FROM Hospital hosp 
LEFT JOIN `Order` ord  ON ord.HospitalID = hosp.HospitalID
LEFT JOIN OrderItem oi on oi.OrderID = ord.OrderID
LEFT JOIN Item itm on itm.ItemID = oi.ItemID; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM