SQL - 根据输出生成列

时间:2016-09-04 08:29:59

标签: mysql sql isql

这是我的问题。我有一个包含2个强实体(事件和员工)的数据库。每个活动都可以有多名员工作为助理,并有一名员工作为领导者。所以我在事件中有一个外键leaderID,并创建了一个连接员工和事件的弱实体助手。

我想要的是显示每个事件的所有员工姓名,adventureCode和startDate以及他们是否是领导者。像:

GR01  2016/09/18  Trudy Lee    Leader 
GR01  2016/09/18  Sonia Chen   Assistant 
GR01  2016/09/18  Henry Blake  Assistant 
YV02  2016/09/17  John Bull    Leader

我不知道如何获得额外的第4列,因为它不在数据库中。

CREATE TABLE employee(
    empID   varchar(5) PRIMARY KEY,
    name    varchar(30)
);

CREATE TABLE event(
    adventureCode   varchar(5),
    startDate       varchar(20),
    leaderID        varchar(5) NOT NULL,
    PRIMARY KEY (adventureCode,startDate),
    FOREIGN KEY (leaderID) REFERENCES employee (empID),
    FOREIGN KEY (adventureCode) REFERENCES adventure (adventureCode)
);

CREATE TABLE assistant(
    empID           varchar(10),
    startDate       varchar(20),
    adventureCode   varchar(5),
    PRIMARY KEY     (empID,startDate,adventureCode),
    FOREIGN KEY     (empID) REFERENCES employee (empID),
    FOREIGN KEY     (adventureCode,startDate) REFERENCES event (adventureCode,startDate)
);

欢迎任何帮助

1 个答案:

答案 0 :(得分:3)

您可以使用CASE EXPRESSION生成此列COALESCE()LEFT JOIN

SELECT e.empID,
       e.Name,
       COALESCE(ev.adventureCode,a.adventure_code) as adventure_code,
       COALESCE(ev.startDate,a.startdate) as startdate,
       CASE WHEN ev.leaderID IS NOT NULL THEN 'Leader' ELSE 'Assistant' END as pos_col
FROM employee e
LEFT JOIN `event` ev
 ON(ev.leaderID = e.empID)
LEFT JOIN assistant a
 ON(e.empID = a.empID)