MySQL-基于输出生成列
作者:互联网
这是我的问题.我有一个包含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)
);
任何帮助都将受到欢迎
解决方法:
您可以使用CASE表达式生成此列,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)
标签:isql,sql,mysql 来源: https://codeday.me/bug/20191118/2026448.html