2

Here is the requirement

I have two tables like below, OrderList is a data table which include 3 fields stored StaffId which is a foreign key from staff table. Noted that some records may not have a value in this table.

OrderList

OrderId Marketing_Staff_ID Finance_Staff_Id ManagerId
1       STAFF001           STAFF002         STAFF003
2                          STAFF005         STAFF003
3       STAFF004           STAFF004         STAFF003
4       STAFF001           STAFF002         STAFF003
5       STAFF001                            STAFF007

Staff

Staff_Id Staff_Name
STAFF001 Jack C.K.
STAFF002 William. C
STAFF005 Someone

I want to write a SQL statement can also select staff name for each record form OrderList, (For these records without staff ID, leave N/A in the name field)

OrderId Mkt StaffID Name       Finance StaffId  Name      ManagerId, Name
1       STAFF001    Jack C.K.  STAFF002         William.  STAFF003   Chan.Chi

So how can I write the SQL? Left join or sth?

Thank you very much as I am really a beginner in SQL.

4

1 回答 1

5

你需要多个LEFT JOINs:

select ol.orderid,
       ol.marketing_staff_id,
       coalesce(ms.staff_name, 'n/a') as marketing_name,
       ol.finance_staff_id,
       coalesce(fi.staff_name, 'n/a') as finance_name
from orderlist as ol
  left join staff as ms on ms.staff_id = ol.marketing_staff_id
  left join staff as fi on fi.staff_id = ol.finance_staff_id

我将由您来为经理添加加入。

以上是 ANSI SQL,应该适用于每个 DBMS。您的 DBMS 可能不支持coalesce简单地将NULL值替换为不同值的功能。在这种情况下,您需要查看 DBMS 的手册。

于 2012-09-26T07:00:15.740 回答