SQL - 根据输出生成列

SQL - Generate column based on output

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

我想要的是显示每个事件的所有员工姓名、冒险代码和开始日期,以及他们是否是领导者。喜欢:

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)
);

欢迎任何帮助

您可以使用 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)